/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Album.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */

var GLOBAL = GLOBAL || {};
GLOBAL.user = {
    area: "sh"
};
GLOBAL.currentDate = Com.date.getCurrentDate();



define(
    '../ancestor/Ancestor',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        window.Ancestor = window.Ancestor || {
            version: '1.0'
        };


    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file:   Album.Crop.js
 * @path:   js-src/album/
 * @desc:   截图用插件
 * @author: gengwei@qiyi.com
 * @date:   2013-05-10
 */
define(
    '../ancestor/Ancestor.Crop',['require','exports','module'],function(require, exports, module) {


        ///import js-src/lib/
        ///import js-src/com/

        (function($, undefined) {
            $.widget('ui.imageCrop', {
                options: {
                    'gallery': null,
                    'cropimg': null,
                    'results': null
                },
                $container: null,
                _jCorpObj: null,
                _scaleInUse: null,
                _create: function(options) {
                    this.options = $.extend({}, this.options, options);
                    this.$container = this.element;
                    this._bindEvents(options);
                    this.$container.data('imageCrop', this);
                },
                enable: function() {
                    this.$container.find('input, button').attr('disabled', false);
                    this.$container.find('div.operation').removeClass('disabled');
                },
                disable: function() {
                    this.$container.find('input, button').attr('disabled', true);
                    this.$container.find('div.operation').addClass('disabled');
                },
                getValue: function() {
                    var $results = this.$container.find(this.options.results);
                    var data = {};
                    $results.find('button').each(function(index, element) {
                        var $button = $(this);
                        var width = $button.data('width');
                        var height = $button.data('height');
                        var imgsrc = $button.data('imgsrc');
                        var coord = $button.data('coord');
                        if (imgsrc && coord) {
                            data[width + '-' + height] = {
                                index: index,
                                imgsrc: imgsrc,
                                spath: $button.data('spath'),
                                w: width,
                                h: height,
                                x1: Math.floor(coord.x),
                                y1: Math.floor(coord.y),
                                x2: Math.floor(coord.x2),
                                y2: Math.floor(coord.y2),
                                data: $button.data('data') || {}
                            };
                        }
                    });
                    return data;
                },
                setValue: function(value) {
                    var that = this;
                    var $results = this.$container.find(this.options.results);
                    var $gallery = this.$container.find(this.options.gallery);
                    var findImage = function(imgsrc) {
                        var $image = null;
                        $gallery.find('img').each(function(index, element) {
                            if (imgsrc == $(this).attr('src')) {
                                $image = $(this);
                            }
                        });
                        return $image;
                    };
                    $results.find('button').each(function(index, element) {
                        var $button = $(this);
                        var width = $button.data('width');
                        var height = $button.data('height');
                        var data = value[width + '-' + height];
                        var coord, imgsrc, $image;
                        if (!data && !$image) {
                            return;
                        }
                        imgsrc = data.imgsrc;
                        $image = findImage(imgsrc);
                        coord = {
                            x: data.x1,
                            y: data.y1,
                            x2: data.x2,
                            y2: data.y2,
                            w: data.x2 - data.x1,
                            h: data.y2 - data.y1
                        };
                        $button.find('.preview').empty().html('<img src="' + imgsrc + '" />');
                        $button.data('imgsrc', imgsrc);
                        $button.data('coord', coord);
                        $button.data('spath', data.spath);
                        $button.data('data', data.data);
                        if ($image) {
                            that._updateCoord.call(that, coord, $button, $image.data('width'), $image.data('height'));
                        }
                    });
                },
                addImages: function(images, callback) {
                    var $gallery = this.$container.find(this.options.gallery);
                    var gallery = this.$container.find('.slideshow').data('gallery');
                    var oldTotal;
                    var total = images.length;
                    var afterImageLoad = function() {
                        total--;
                        if (0 === total) {
                            if (callback) {
                                callback();
                            }
                        }
                    };
                    $.each(images, function(index, image) {
                        var $imgdiv, data;
                        data = {
                            imgsrc: image.url
                        };
                        if (image.shot) {
                            // 视频截图
                            data.type = 1;
                            data.area = image.area;
                        } else {
                            // 数据回填    
                            data.spath = image.spath;
                            data.type = 0;
                            data.data = image.data;
                        }
                        $imgdiv = $('<img src="' + data.imgsrc + '">');
                        $imgdiv.data(data).load(function(e) {
                            Com.Image.procThumbnail($(this), 128, 80);
                            afterImageLoad();
                        }).error(function(e) {
                            afterImageLoad();
                        });
                        $gallery.append($('<li style="position:relative" class="item" />').append($imgdiv));
                    });
                    oldTotal = gallery.totalItems;
                    gallery.update();
                    gallery.scrollTo(oldTotal);
                },
                // 计算初始截图位置
                _calcInitCoord: function(origWidth, origHeight, scaleWidth, scaleHeight) {
                    var left, top;
                    var newWidth = origWidth * 2 / 3;
                    var newHeight = newWidth * scaleHeight / scaleWidth;
                    if (newHeight > origHeight) {
                        newHeight = origHeight;
                        newWidth = newHeight * scaleWidth / scaleHeight;
                    }
                    newWidth = Math.floor(newWidth);
                    newHeight = Math.floor(newHeight);
                    left = Math.floor((origWidth - newWidth) / 2);
                    top = Math.floor((origHeight - newHeight) / 2);
                    return {
                        x: left,
                        y: top,
                        x2: left + newWidth,
                        y2: top + newHeight
                    };
                },
                // 选择一个比例
                _selectScale: function($button) {
                    var imgsrc = $button.data('imgsrc');
                    var coord = $button.data('coord');
                    $button.data('inuse', true);
                    this._scaleInUse = {
                        width: $button.data('width'),
                        height: $button.data('height'),
                        button: $button,
                        imgsrc: imgsrc,
                        coord: coord
                    };
                    if (imgsrc && coord) {
                        // if is already cropped...
                        this._selectOrigImg(imgsrc);
                    } else {
                        this._selectOrigImg(imgsrc);
                    }
                },
                // 选择一个原始图
                _selectOrigImg: function(imgsrc) {
                    var $gallery = this.$container.find(this.options.gallery);
                    var $cropimg = this.$container.find(this.options.cropimg);
                    $image = $gallery.find('img').filter(function(index, element) {
                        return $(this).attr('src') == imgsrc;
                    });
                    if ($image.length > 0) {
                        $image.click();
                    } else if (1 == $gallery.find('img').length) {
                        $gallery.find('img').eq(0).click();
                    } else {
                        $gallery.find('li').removeClass('active');
                        $cropimg.empty();
                    }
                },
                // 设置 jCorp 对象
                _setupJCorp: function($image, updateCoords, scaleInUse, coord) {
                    var that = this;
                    this._jCorpObj && this._jCorpObj.destroy();
                    this._jCorpObj = null;
                    $image.Jcrop({
                        keySupport: false,
                        onSelect: updateCoords,
                        onChange: updateCoords,
                        aspectRatio: scaleInUse.width / scaleInUse.height,
                        trueSize: [$image.data('width'), $image.data('height')]
                    }, function() {
                        that._jCorpObj = this;
                        that._jCorpObj.animateTo([coord.x, coord.y, coord.x2, coord.y2]);
                    });
                },
                // 绑定事件
                _bindEvents: function() {
                    var that = this;
                    var $gallery = this.$container.find(this.options.gallery);
                    var $cropimg = this.$container.find(this.options.cropimg);
                    var $results = this.$container.find(this.options.results);
                    var $confirm = this.$container.find(this.options.confirm);
                    // 选择裁剪比例
                    $results.delegate('a', 'click', function(e) {
                        e.preventDefault();
                    });
                    $results.delegate('button', 'click', function(e) {
                        var $button = $(this);
                        $button.siblings().removeClass('active');
                        $button.addClass('active');
                        that._selectScale($(this));
                    });
                    // 缩略图的点击事件

                    $gallery.delegate('img', 'click', function(e) {
                        var $thumbimg = $(this),
                            $imgToCrop, $button;
                        var t, scaleWidth, scaleHeight, imageWidth, imageHeight, cropWidth, cropHeight;
                        var imgsrc = $thumbimg.attr('src'),
                            coord;
                        var scaleInUse = that._scaleInUse;
                        // test if is possible to do this action
                        if ($thumbimg.parents('div.operation').hasClass('disabled')) {
                            return;
                        }
                        if (null === scaleInUse) {
                            alert('请先选择缩略图的比例');
                            return false;
                        }
                        if (true === $thumbimg.data('loading')) {
                            alert('该图片现在暂时不可用，请等待上传完成');
                            return false;
                        }
                        // get current scale button
                        $button = scaleInUse.button;
                        imageWidth = $thumbimg.data('width');
                        imageHeight = $thumbimg.data('height');
                        coord = $button.data('coord');
                        // add style to selected image
                        $gallery.find('li').removeClass('active');
                        $thumbimg.parent().addClass('active');
                        // set corp area style and set image to crop area
                        cropWidth = $cropimg.outerWidth() - 2;
                        cropHeight = $cropimg.outerHeight() - 2;
                        t = Com.Image.resizeInside($thumbimg, cropWidth, cropHeight);
                        $imgToCrop = $('<img src="' + imgsrc + '" width="' + t.width + '" height="' + t.height + '">');
                        $imgToCrop.data('width', imageWidth).data('height', imageHeight).data('spath', $thumbimg.data('spath'));
                        $cropimg.css({
                            width: t.width,
                            height: t.height,
                            padding: t.top + 'px ' + (cropWidth - t.width - t.left) + 'px ' + (cropHeight - t.height - t.top) + 'px ' + t.left + 'px'
                        });
                        $cropimg.empty().append($imgToCrop);
                        //
                        if (scaleInUse.imgsrc != imgsrc) {
                            coord = that._calcInitCoord(imageWidth, imageHeight, scaleInUse.width, scaleInUse.height);
                        }
                        // set JCrop
                        $button.data('imgsrc', imgsrc);
                        $button.data('spath', $thumbimg.data('spath') || null);
                        $button.find('.preview').empty().html('<img src="' + imgsrc + '" />');
                        that._setupJCorp($imgToCrop, function(coord) {
                            that._updateCoord.call(that, coord, $button, imageWidth, imageHeight, true);
                        }, scaleInUse, coord);
                    });


                },
                _updateCoord: function(coord, $button, imageWidth, imageHeight, flush) {
                    var scale = coord.h / $button.find('.preview').height();
                    var newWidth = Math.floor(imageWidth / scale);
                    var newHeight = Math.floor(imageHeight / scale);
                    var left = Math.floor(coord.x / scale);
                    var top = Math.floor(coord.y / scale);
                    if (flush) {
                        $button.data('data', null);
                    }
                    $button.data('coord', coord);
                    $button.find('.preview img').css({
                        width: newWidth,
                        height: newHeight,
                        marginTop: 0 - top,
                        marginLeft: 0 - left
                    });
                }
            });
            $.extend($.ui.imageCrop, {
                uuid: 0,
                _isShow: false
            });
        }(jQuery));

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../ancestor/Ancestor.Config',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    Ancestor.Config = (function() {
        var REQUEST_FAIL = "接口响应超时,请稍后再试！";
        var QICHUAN = {

            //image_requestURL: 'http://upload.iqiyi.com/request_image_upload',
            image_requestURL_test: 'http://upload.iqiyi.com/request_image_upload',

            image_uploadURL: 'http://upload.iqiyi.com/image_upload',
            image_uploadURL_inner: 'http://upload.qiyi.domain/image_upload',
            image_uploadURL_test: 'http://upload.iqiyi.com/image_upload',

            deviceId: 'LEGO-uploader',
        };

        var EPG_AUTH = {

            From: 'frontend', // 来源
            key: '7dpHGKMy4hAh3DmC' // 密钥

        };

        var CONFIGS_API = {
            url: '/api/configs'
        };

        // 直转点 频道名称
        var CATEGORY_NAME = [];

        // 直播类型
        var LIVE_TYPE = [];

        // 频道分类
        var CHANNEL_TYPE = [];


        // 日志分类
        var LOG_TYPE = [];

        // 备播库标色提示
        var APC_WARNING = {
            NORMAL: 'black',
            RED: 'red',
            ORANGE: '#ffa800'
        };

        var PLATFORM_TYPE = null;
        var PLATFORM_REFER = null;

        // 奇谱url
        var QIPU_URL = (function() {
            var qipuUrl = auth.dev() ? 'http://qipu-test.qiyi.domain/int/entity/nocache/${QIPUID}.json' : 'http://qipu.qiyi.domain/int/entity/nocache/${QIPUID}.json';
            return qipuUrl;
        })();

        return {
            EPG_AUTH: EPG_AUTH,
            LIVE_TYPE: LIVE_TYPE,
            CHANNEL_TYPE: CHANNEL_TYPE,
            QICHUAN: QICHUAN,
            CONFIGS_API: CONFIGS_API,
            LOG_TYPE: LOG_TYPE,
            APC_WARNING: APC_WARNING,
            PLATFORM_REFER: PLATFORM_REFER,
            PLATFORM_TYPE: PLATFORM_TYPE,
            QIPU_URL: QIPU_URL,
            REQUEST_FAIL: REQUEST_FAIL,
            CATEGORY_NAME:CATEGORY_NAME
        };


    })();

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../ancestor/Ancestor.Util',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/

    Ancestor.Util = (function() {

        Date.prototype.format = function (format) {
        var o = {
                  "M+" : this.getMonth() + 1, //month
                  "d+" : this.getDate(), //day
                  "h+" : this.getHours(), //hour
                  "m+" : this.getMinutes(), //minute
                  "s+" : this.getSeconds(), //second
                  "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
                  "S" : this.getMilliseconds() //millisecond
              }

              if (/(y+)/.test(format)) {
                  format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
              }

              for (var k in o) {
                  if (new RegExp("(" + k + ")").test(format)) {
                      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                  }
              }
              return format;
          };

        // 组装 sign
        var authorization = function(options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return md5(rawSign);
        };

        /**
         * 设置截图编辑的整体，包括截图、幻灯片、上传三个部分
         * @param $imgcrop Object 整体的DOM结构，jQuery Object
         * @param images Array<String> 初始化用的图片URL数组
         * @param width 如果有幻灯片的话，幻灯片部分的宽度
         */
        var imageCrop = function($imgcrop) {
            // try{
            var $slideshow = $imgcrop.find('.slideshow');
            var $enableBtn = $imgcrop.find('button.button-enable');
            var $uploadBtn = $imgcrop.find('input.uploadButton');
            var $btnOnline = $imgcrop.find('button.button-online');
            var gallery, t, flag;
            // 设置下面的缩略图
            $slideshow.gallery({
                thumbnail: '.item',
                prevButton: $slideshow.find('button.left'),
                nextButton: $slideshow.find('button.right')
            });
            gallery = $slideshow.data('gallery');
            t = gallery.totalItems;
            // 设置上传图片按钮
            if ($uploadBtn.length) {
                $uploadBtn.uploadDialog({
                    gallery: $imgcrop.find('.gallery'),
                    onStart: function() {
                        gallery.update();
                        gallery.scrollTo(t);
                    }
                });
            }
            $(window).resize(function(e) {
                gallery.update();
            });
            // 设置截图控件
            $imgcrop.imageCrop({
                'gallery': '.gallery',
                'cropimg': '.cropimg',
                'results': '.results'
            });
            // 设置激活按钮
            if ($('#_entityId').val()) {
                $enableBtn.click(function(e) {
                    $imgcrop.data('imageCrop').enable();
                    $enableBtn.attr('disabled', true);
                    gallery.scrollTo(0);
                });
                $imgcrop.data('imageCrop').disable();
                $enableBtn.attr('disabled', false);
            } else {
                $imgcrop.data('imageCrop').enable();
                $enableBtn.attr('disabled', true);
                $enableBtn.hide();
            }
          $imgcrop.find('.header input').enable();
            if ('1' === $('#ThriftVideoMakeStatus').val() && '1' != $('#entityType').val()) {
                $btnOnline.show();
            } else {
                $btnOnline.hide();
            }
            // 设置在线视频截图
            /*
            if ($btnOnline.length) {
                $('#AlbumEditVideoShot').videoShot({
                    onFinish: function(area, images) {
                        var data = [];
                        $.each(images, function(index, image) {
                            data.push({
                                shot: true,
                                url: image,
                                area: area
                            });
                        });
                        $imgcrop.data('imageCrop').addImages(data);
                    }
                });
                $btnOnline.click(function(e) {
                    $('#AlbumEditVideoShot').dialog('open');
                });
            }
            */

            // }catch(e){}
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            }).trigger('keyup');
            $des.keyup();
        };

        getParam = function($obj) {

            var $container = $obj;
            var params = {};
            var $form = $obj;

            var $elements = $.makeArray($form.prop('elements')).filter(function() {
                return true; //this.name; 
            });

            var name;
            var key;
            $.each($elements, function() {
                name = this.name;
                if (name) {

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $.trim($(this).val()) || '';

                }

            });

            params['logoUrl'] = imageObject($obj);
            return params;

        };

        imageObjectEcho = function($form, value) {

            if (value) {
                value = ('object' == typeof(value) ? value : JSON.parse(value || '[]'));
            } else {
                value = null;
            }
            if (!value) {
                return;
            }

            var imageObject = value;
            var filterType = function(type) {
                var imageData = null;
                $.each(imageObject, function(index, value) {
                    if (value.useType == type) {
                        imageData = value;
                    }
                });
                return imageData;
            };
            var spathToURL = function(images, spath) {
                var url = null;
                $.each(images, function(index, image) {
                    if (spath === image.spath) {
                        url = image.url;
                    }
                });
                return url;
            };

            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var imageCrop = $croparea.data('imageCrop');
                var useType = 699; //parseInt($croparea.find('input[name="useType"]').val(), 10);
                var imageData = filterType(useType);
                var imageRank = imageData && imageData.contentRank ? imageData.contentRank : 0;
                var images = [],
                    results = {};

                if (!imageData) {
                    return;
                }

                // 回显图片分级的选项
                $croparea.find('input[name^="contentRank"]').each(function(key, value) {
                    value.checked = (imageRank == value.value);
                });

                $.each(imageData.materials, function(index, material) {
                    //images.push(material.bigThumbUrl || material.location);
                    // todo: type
                    images.push({
                        spath: material.location,
                        url: material.url,
                        data: material
                    });
                });
                $.each(imageData.images, function(index, image) {
                    var scale = image.editInfo.scale;
                    var cutPosition = image.editInfo.cutPosition.split(',');
                    var width = scale.substring(0, scale.indexOf(':'));
                    var height = scale.substring(scale.indexOf(':') + 1);
                    results[width + '-' + height] = {
                        spath: image.materialLocation,
                        imgsrc: spathToURL(images, image.materialLocation),
                        w: width,
                        h: height,
                        x1: parseInt(cutPosition[0], 10),
                        y1: parseInt(cutPosition[1], 10),
                        x2: parseInt(cutPosition[0], 10) + parseInt(cutPosition[3], 10),
                        y2: parseInt(cutPosition[1], 10) + parseInt(cutPosition[2], 10),
                        data: image
                    };
                });
                imageCrop.addImages(images, function() {
                    imageCrop.setValue(results);
                });
            });
        };


        imageObject = function($form) {
            var imageObject = [];
            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var useType = parseInt($croparea.find('input[name="useType"]').val(), 10);
                var contentRank = parseInt($croparea.find('input[name^="contentRank"]:checked').val(), 10) || 0; // 默认图片分级是无分级，0
                var testFlag = 0;
                var imageData = {
                    materials: [],
                    images: [],
                    useType: 699, //useType,
                    contentRank: contentRank // 图片分级的需求，默认是无分级
                };
                $croparea.find('.gallery img').each(function(index, material) {
                    var $material = $(material);
                    if (true === $material.data('loading')) {
                        return;
                    }
                    var tmp = $material.data('data') || {
                        // @todo
                        'location': $material.data('spath') || '',
                        'url': $material.attr('src'),
                        'fromType': $material.data('type'),
                        'area': 'bj', //$material.data('area'),
                        'width': $material.data('width'),
                        'height': $material.data('height')
                    };
                    imageData.materials.push(tmp);
                    testFlag++;
                });
                $.each($croparea.data('imageCrop').getValue(), function(index, value) {
                    var tmp = $.extend(value.data, {
                        materialLocation: value.spath || value.imgsrc || '',
                        editInfo: {
                            cutPosition: [value.x1, value.y1, value.y2 - value.y1, value.x2 - value.x1].join(','),
                            scale: value.w + ':' + value.h
                        }
                    });
                    imageData.images.push(tmp);
                    //testFlag |= Math.pow(2, value.index);
                });
                var type = $form.find('input[name="entityType"]').val();
                if (('0' == type && (parseInt($form.find('input[name="video.id"]').val(), 10) > 0))
                    // 如果是节目且专辑id禁用表示编目修改
                    || ('1' === type && (parseInt($form.find('input[name="album.id"]').val(), 10) > 0))
                    // 如果是专辑有#_entityId表示修改
                    || ($form.find('input[name=pilosityType]').val() && $form.find('input[name=baseId]').val())
                    // 如果是一文多发有pilosity且有baseId表示修改
                ) {
                    // 节目，专辑, 一文多发，兼容旧的，修改的时候不验证截图
                    testFlag = 99;
                }
                $croparea.find('input[name="_image_crop_' + useType + '"]').val(testFlag);
                imageObject.push(imageData);
            });
            return JSON.stringify(imageObject);
        };


        getUrlId = function(name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        fillFieldNameWhenChangeSelect = function($form, elClazzName, fieldClazzName) {
            $form.find('.' + elClazzName).on('change', function() {
                var value = $(this).val();
                var $input = $(this).closest('.control-group').find('.' + fieldClazzName);
                $input.attr('name', value);
            });
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            });
            $des.keyup();
        };

        var getUploadFiles = function(options, isNew) {
            if (isNew && isNew === true) {
                return new Ancestor.Upload(options);
            }
            if (!uploadFiles) {
                uploadFiles = new Ancestor.Upload(options);
            } else {
                uploadFiles.update(options);
            }
            return uploadFiles;
        };

        var isNormal = function(user) {

            return true;
        };



        // 打开对话框
        var openDlg = function(obj, title, width, height) {

            height = height || 'auto';
            var $container = obj;

            $container.dialog({
                title: title,
                appendTo: null,
                modal: true,
                width: width,
                height: height,
                position: ['top', 'top+20'],

                open: function() {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                },
                close: function() {

                }
            });
        };

        var highlight = function(data, key, term) {
            data.forEach(function(item, i) {
                key = key || 'label';
                var label = item[key];
                if (!label || !term) {
                    return;
                }
                item[key] = (item[key] + '').replace(new RegExp('(' + term + ')', 'i'), '<b>$1</b>');
                // 高亮未输入部分
                // if (label.toLowerCase().indexOf(term.toLowerCase()) == 0) {
                //     item[key] = item[key].substr(0, term.length)
                //                   + '<b>'
                //                   + item[key].substr(term.length) + '</b>';
                // }
            });
        };

        var updateParamsBySettings = function(params, entity) {
            if (!params) {
                params = {};
            }

            if (entity.checkPublishType == 1) {
                params["filter_EQI_pagePublishStatus"] = 1;
            }
            if (entity.checkCopyRightType == 1) {
                params["filter_GTI_copyrightOwnerId"] = 0;
            }
            if (entity.checkBossType == 0) {
                params["filter_INI_isPurchase"] = "0,-100";
            } else if (entity.checkBossType == 1) {
                params["filter_INI_isPurchase"] = "1,2";
            }
            var platformTypeResponse = Ancestor.Config.PLATFORM_TYPE;
            $.each(platformTypeResponse, function(i, element) {
                //   params["region_" + element.val] = 0;
                if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["region_" + element.val] = 1;
                }
            });
            var platformReferResponse = Ancestor.Config.PLATFORM_REFER;
            $.each(platformReferResponse, function(i, element) {
                //   params["filter_EQI_" + element.val] = 0;
                if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["filter_EQI_" + element.val] = 1;
                }

            });
            console.log(" params:" + JSON.stringify(params));

            return params;
        };

        var createSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }

                    var fetchData = function() {
                        Ancestor.Dao.getSuggestData(url, param, function(json) {
                            var ret = dataProcess.call(self, json, term);

                            var runNext = function(ret) {
                                if ($.isArray(options.sortBy)) {
                                    sortBy.apply(self, [ret].concat(options.sortBy));
                                } else if ($.isFunction(options.onSortBy)) {
                                    options.onSortBy.apply(self, [ret, term]);
                                }

                                if (options.highlight) {
                                    if ($.isFunction(options.onHighlight)) {
                                        options.onHighlight.apply(self, [ret, term]);
                                    } else {
                                        highlight(ret, null, term);
                                    }
                                }
                                result = ret;
                                if ($.isFunction(options.onLoad)) {
                                    options.onLoad.apply(self, [result, term]);
                                }
                                response(result);
                            };

                            if (options.needFetchMore) {
                                options.fetchMore(ret, runNext);
                            } else {
                                runNext(ret);
                            }
                        });
                    };

                    if (options.needPreProcess) {
                        var channelId = Com.url.getParameter("id");
                        Ancestor.Dao.platSettings({
                            channelId: channelId
                        }, function(json) {
                            if (json.code === 'A00000') {
                                param = updateParamsBySettings(param, json.data);
                                fetchData();
                            }
                        });
                    } else {
                        fetchData();
                    }


                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {


                //////////////////suggest选择后回显设置/////////////////////
                //  ui.item.value=ui.item.name;


                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        };

        var qitan = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width80">${resourceId}</span>' +
                '<span class="contract-width250">{{html name}}</span>' +
                '<span class="contract-width80">${addDate}</span>' +
                '</div></div>';

            var title = {
                resourceId: '评论ID',
                name: '评论名称',
                addDate: '创建时间'
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                url: 'http://api.t.iqiyi.com/qx_api/resource/get_id_by_name',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                otherParam: $.extend({
                    'page_size': 10,
                    'resource_type': $(el).data('type') || 1
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'name': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data.ids;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                label: item.name,
                                value: item.resourceId,
                                id: item.resourceId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };


        var universalCodeCreateSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }
                    Ancestor.Dao.getuniversalCodeData(url, param, function(json) {
                        var ret = dataProcess.call(self, json, term);
                        if ($.isArray(options.sortBy)) {
                            sortBy.apply(self, [ret].concat(options.sortBy));
                        } else if ($.isFunction(options.onSortBy)) {
                            options.onSortBy.apply(self, [ret, term]);
                        }

                        if (options.highlight) {
                            if ($.isFunction(options.onHighlight)) {
                                options.onHighlight.apply(self, [ret, term]);
                            } else {
                                highlight(ret, null, term);
                            }
                        }
                        result = ret;
                        if ($.isFunction(options.onLoad)) {
                            options.onLoad.apply(self, [result, term]);
                        }
                        response(result);
                    });

                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {
                ui.item.value = ui.item.code;
                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        }

        var universalCode = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width250">${code}</span>' +
                '<span style="border-right:none;">${name}</span>' +
                '</div></div>';

            var title = {
                code: '直播频道首拼音',
                name: '直播频道名称',
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);

            universalCodeCreateSuggest(el, $.extend(true, {

                url: '/api/channel/codelist',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'key': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.name,
                                code: item.code,
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };



        var qitanSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                qitan($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.id);
                        //console.log( $input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };

        var universalCodeSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                universalCode($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.code);
                        //console.log($input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };



        var alternatePlayCollection = function(el, options) {

            var tpl = '<div class="contract-item">' +
                '<span class="contract-width100" style="color:${needAlert}">${qipuId}</span>' +
                '<span class="contract-width150" style="color:${needAlert}">${displayName}</span>' +
                '<span class="contract-width60" style="color:${needAlert}">${channelName}</span>' +
                '<span class="contract-width120" style="color:${needAlert}">${copyrightEndTime}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${isPurchase}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${pagePublishStatus}</span>' +
                '</div>';

            var _ppsClientArr = [
                "ANDRIOD_PPSControl",
                "ANDROID_PAD_PPSControl",
                "IOS_JAILBREAK_PPSControl",
                "IPAD_PPSControl",
                "IPHONE_PPSControl",
                "MAC_PPSControl",
                "PC_CLIENT_PPSControl",
                "WIN8_PPSControl",
                "WINDOWS_PHONE_PPSControl"
            ];

            var _platClientArr = [
                "ANDRIOD_PPS",
                "ANDROID_PAD_PPS",
                "IOS_JAILBREAK_PPS",
                "IPAD_PPS",
                "IPHONE_PPS",
                "MAC_PPS",
                "PC_CLIENT_PPS",
                "WIN8_PPS",
                "WINDOWS_PHONE_PPS"
            ];

            var platformRefer = "platformRefer",
                platSettings = "platSettings",
                platforms = "platforms";

            var title = {
                qipuId: '奇谱ID',
                displayName: '显示名称',
                channelName: '频道',
                copyrightEndTime: '版权到期时间',
                isPurchase: '是否付费',
                pagePublishStatus: '发布状态'
            };

            var checkPlatforms = [];
            Ancestor.Dao.getType({
                type: 'PlayPlatform'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_TYPE = json.data;
                    checkPlatforms = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });


            Ancestor.Dao.getType({
                type: 'PlatformRefer'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_REFER = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });

            var decodePlayPlatform = function(elementChild) {
                var locationControl = null;
                var platformObject = {
                    platName: null,
                    locationArr: []
                }
                platformObject.platName = elementChild["play_platform"];
                platformObject.status = 'online';
                if (elementChild["default_control"] != null) {
                    if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                        platformObject.status = "offline";
                    }
                }
                if ($.isArray(elementChild["region_control"])) {
                    $.each(elementChild["region_control"], function(indexRegion, regionElement) {
                        if ($.isArray(regionElement["location"])) {
                            $.each(regionElement["location"], function(j, child) {
                                if(child.hasOwnProperty("province_id")){
                                    if (child["province_id"] != 95 && child["province_id"]  != 148 && child["province_id"]  != 228) {
                                        locationControl = regionElement["location_control"];
                                        if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                            platformObject.locationArr.push(child["province_id"]);
                                            console.log("break regionElement location");
                                        }
                                    }
                                }
                            })
                        }
                    })
                }
                return platformObject;
            };

            var checkPPSClient = function(data) {
                if (data.qipuId == '奇谱ID') {
                    data['needAlert'] = 0;
                    return data;
                }

                var ppsCheckList = [];
                $.each(_ppsClientArr, function(i, ppsKey) {
                    if (!data.hasOwnProperty(ppsKey) || data[ppsKey] == 0) {
                        ppsCheckList.push(ppsKey);
                    }
                });

                if (ppsCheckList.length > 0) {
                    data['needAlert'] = 'red';
                } else {
                    data['needAlert'] = 'black';
                }
                return data;
            };

            var checkQipuData = function(data) {
                var playControlArr = data.QIPUDATA.access_play_control;
                if ($.isArray(playControlArr)) {
                    var temp = {};
                    $.each(playControlArr, function(index, elementChild) {
                        var platformObject = decodePlayPlatform(elementChild);
                        if (platformObject.platName != null) {
                            temp[platformObject.platName] = platformObject;
                        }
                    });

                    var qipuPlatformData = [];
                    var qipuRegionData = [];
                    var hintMsgObj = {
                        missQIYIClient: false,
                        missPPSClient: false,
                        missQIYIRegion: false,
                        missPPSRegion: false
                    };
                    $.each(checkPlatforms, function(index, element) {
                        var ppsFlag = element.val.indexOf("PPS") !== -1;
                        if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                            qipuPlatformData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSClient = true;
                            } else {
                                hintMsgObj.missQIYIClient = true;
                            }
                        }
                        if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                            qipuRegionData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSRegion = true;
                            } else {
                                hintMsgObj.missQIYIRegion = true;
                            }
                        }
                    });

                    if (hintMsgObj.missPPSClient || hintMsgObj.missQIYIClient) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.RED;
                    } else if (hintMsgObj.missPPSRegion || hintMsgObj.missQIYIRegion) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.ORANGE;
                    } else {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;
                    }

                }

                return data;
            };

            var getHtmlByData = function(data) {

                if (typeof(data.copyrightEndTime) == "number" || typeof(data.copyrightBeginTime) == "number") {

                    if (data.copyrightEndTime == '-100' || data.copyrightBeginTime == '-100') {
                        data.copyrightEndTime = "永久版权";
                    } else if (new Date() > data.copyrightEndTime || new Date() < data.copyrightBeginTime) {
                        data.copyrightEndTime = "过期";
                    } else {
                        data.copyrightEndTime = Com.date.format(new Date(data.copyrightEndTime), "yyyy-MM-dd hh:mm:ss");
                    }
                }

                //if(data.copyrightEndTime=="过期")
                //  return '';

                switch (data.isPurchase) {
                    case 0:
                    case -100:
                        data.isPurchase = "免费";
                        break;
                    case 1:
                        data.isPurchase = "收费";
                        break;
                    case undefined:
                        data.isPurchase = ""
                        break;

                    default:
                        data.isPurchase = data.isPurchase + ""
                }

                switch (data.pagePublishStatus) {
                    case 0:
                        data.pagePublishStatus = "未发布";
                        break;
                    case 1:
                        data.pagePublishStatus = "已发布";
                        break;
                    case 2:
                        data.pagePublishStatus = "页面下线";
                        break;
                    case 3:
                        data.pagePublishStatus = "页面备用"
                        break;
                    case undefined:
                        data.pagePublishStatus = ""
                        break;

                    default:
                        data.pagePublishStatus = data.pagePublishStatus + "";
                }

                var htmls = [];
                data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;

                if (data.hasOwnProperty('QIPUDATA')) {
                    data = checkQipuData(data);
                } else {
                    data = checkPPSClient(data);
                }

                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));

                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                //url: 'http://lego.iqiyi.com/suggest/simple-video-area',
                url: 'http://lego.iqiyi.com/apis/search/search-area',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                needFetchMore: true,
                needPreProcess: true,
                otherParam: $.extend({
                    t: 0,
                    filter_GTL_qipuId: 0,
                    //filter_EQI_contentType:1,
                    //'page.orderBy': "createTime",
                    //'page.order': "desc",
                    filter_GEL_duration: 30000,
                    //filter_EQI_pagePublishStatus:1,
                    //filter_INI_isPurchase : "0,-100",
                    //filter_GTI_copyrightOwnerId : 0,
                    //filter_EQI_PadIosControl:1,
                    //filter_EQI_PhoneAndroidControl:1,
                    //filter_EQI_PhoneIosControl:1,
                    //filter_EQI_PcControl:1,
                    //filter_EQI_TvControl:1,
                    //filter_EQI_PcClientControl:1,
                    //filter_EQI_H5Control:1,
                    //filter_EQI_PadAndroidControl:1,
                    //filter_EQI_PadWebControl:1,
                    //region:1,
                    'page.pageSize': 10
                        //                    filter_EQI_ANDRIOD_PPSControl: 1,
                        //                    filter_EQI_ANDROID_PAD_PPSControl: 1,
                        //                    filter_EQI_IOS_JAILBREAK_PPSControl: 1,
                        //                    filter_EQI_IPAD_PPSControl: 1,
                        //                    filter_EQI_IPHONE_PPSControl: 1,
                        //                    filter_EQI_MAC_PPSControl: 1,
                        //                    filter_EQI_PC_CLIENT_PPSControl: 1,
                        //                    filter_EQI_WIN8_PPSControl: 1,
                        //                    filter_EQI_WINDOWS_PHONE_PPSControl: 1,
                        //                    needCookie: true

                    //   pps region 限制
                    //region_ANDROID_PAD_PPS:0,
                    //region_WIN8_PPS:0,
                    //region_MAC_PPS:0,
                    //region_WINDOWS_PHONE_PPS:0,
                    //region_ANDRIOD_PPS:0,
                    //region_IOS_JAILBREAK_PPS:0,
                    //region_IPAD_PPS:0,
                    //region_IPHONE_PPS:0,
                    //region_PC_CLIENT_PPS:0,
                    //   qiyi region 限制
                    //region_ANDROID_PAD_IQIYI:1,
                    //region_ANDROID_PHONE_IQIYI:1,
                    //region_H5_QIYI:1,
                    //region_IOS_PAD_IQIYI:1,
                    //region_IOS_PHONE_IQIYI:1,
                    //region_PAD_WEB_QIYI:1,
                    //region_PC_CLIENT_IQIYI:1,
                    //region_PC_QIYI:1,
                    //region_TV_IQIYI:1,
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'filter_LIKES_displayName': term
                    };
                },

                fetchMore: function(data, callback) {
                    var self = this;
                    self.count = 0;
                    self.ret = [];
                    self.data = data;
                    $.each(data, function(i, item) {
                        Ancestor.Dao.getQipuDataById(item, function(json, t) {
                            if (json) {
                                t.QIPUDATA = json;
                            }
                            self.ret.push(t);
                            self.count++;
                            if (self.count == self.data.length) {
                                callback(self.ret);
                            }
                        });
                    });
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data.result, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.displayName,
                                id: item.qipuId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-backup');
        };

        var alternatePlayCollectionSuggest = function($inputs, options) {
            $inputs.each(function(index, element) {
                var self = this;
                alternatePlayCollection($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.qipuId);
                        //console.log( $input.data('value'));

                        var temp = data.item;
                        data.item = {};

                        data.item['qipuId'] = temp['qipuId'];
                        data.item['displayName'] = temp['displayName'];
                        data.item['contentType'] = temp['contentType'];
                        data.item['duration'] = temp['duration'];
                        data.item['needAlert'] = temp['needAlert'];
                        temp = {};

                        var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val();
                        //console.log(alternatePlayCollection);
                        if (alternatePlayCollection) {
                            alternatePlayCollection = JSON.parse(alternatePlayCollection);
                            var has = false,
                                i;

                            for (var i in alternatePlayCollection) {
                                if (alternatePlayCollection[i].qipuId == data.item.qipuId) {
                                    has = 1;
                                    break;
                                }
                            }

                            i = parseInt(i) + 1;

                            if (!has) {
                                var msg = null;
                                if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                                } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                                } else {
                                    alternatePlayCollection[i] = data.item;

                                    $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                    alternatePlayCollectionAppend({
                                        qipuId: data.item.qipuId
                                    });
                                }

                                if (msg) {
                                    SystemDialog.queryConfirm(msg, function(flag) {
                                        if (flag === true) {
                                            alternatePlayCollection[i] = data.item;

                                            $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                            alternatePlayCollectionAppend({
                                                qipuId: data.item.qipuId
                                            });
                                        }
                                    });
                                }
                            }

                        } else {
                            alternatePlayCollection = {};

                            var msg = null;
                            if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                            } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                            } else {
                                alternatePlayCollection[0] = data.item;

                                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                alternatePlayCollectionAppend({
                                    qipuId: data.item.qipuId
                                });
                            }

                            if (msg) {
                                SystemDialog.queryConfirm(msg, function(flag) {
                                    if (flag === true) {
                                        alternatePlayCollection[0] = data.item;

                                        $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                        alternatePlayCollectionAppend({
                                            qipuId: data.item.qipuId
                                        });
                                    }
                                });
                            }
                        }
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };


        var alternatePlayCollectionAppend = function(v) {
            $('#alternatePlayCollectionIds').append('<span class="ui-suggest-value tagmanagerTag" data-id="' + v.qipuId + '">' + v.qipuId + '<a class="tagmanagerRemoveTag"  onclick="Ancestor.Util.removeAlternatePlayCollection(this)"  title="Remove" href="javascript:;">x</a></span>');
            $('input[name="alternatePlayCollectionInput"]').attr('disabled','disabled');;
        };

        // 删除备播库
        removeAlternatePlayCollection = function(obj) {

            var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val(),
                AlternatePlayCollectionId = $(obj).parent().attr('data-id'),
                alternatePlayCollectionTmp = {};

            alternatePlayCollectionTmp = alternatePlayCollection = JSON.parse(alternatePlayCollection);

            for (var i in alternatePlayCollectionTmp) {
                if (alternatePlayCollectionTmp[i].qipuId == AlternatePlayCollectionId) {
                    delete alternatePlayCollection[i];
                    break;
                }
            }

            if ($.isEmptyObject(alternatePlayCollection)) {
                $('input[name="alternatePlayCollection"]').val('');
                $('input[name="alternatePlayCollectionInput"]').removeAttr('disabled');;
            } else {
                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
            }

            $(obj).parent().remove();
        };



        var getAuth = function(str) {

            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);

            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = md5(str + time + Ancestor.Config.EPG_AUTH.key);

            //console.log(auth);            
            return auth;

        };

        return {
            imageCrop: imageCrop,
            authorization: authorization,
            getParam: getParam,
            getUrlId: getUrlId,
            fillFieldNameWhenChangeSelect: fillFieldNameWhenChangeSelect,
            limitWordCount: limitWordCount,
            getUploadFiles: getUploadFiles,
            isNormal: isNormal,
            openDlg: openDlg,
            qitanSuggest: qitanSuggest,
            universalCodeSuggest: universalCodeSuggest,
            imageObjectEcho: imageObjectEcho,
            getAuth: getAuth,
            alternatePlayCollectionSuggest: alternatePlayCollectionSuggest,
            alternatePlayCollectionAppend: alternatePlayCollectionAppend,
            removeAlternatePlayCollection: removeAlternatePlayCollection,
        };


    })();

});
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 * 
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

define('../ancestor/Ancestor.Grid',['require','exports','module'],function(require, exports, module) {

    Ancestor.Grid = function(options) {};
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        filterDataWhenBatchOper: function(data, filter) {
            filter = filter || function(item) {
                return !item.del;
            };

            data = $.grep(data, function(item) {

                return filter(item);
            });

            return data;
        },
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function(callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [{
                page: 1
            }]);

        },
        getParam: function() {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function() {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function() {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGrid: function() {
            return this.$grid;
        },

        run: function(options, callback) {


            this.bindEvent();
            this.echoQuery();
            this.initGrid.call(this, options, callback);

        },

        setType: function(type) {
            this.options.type = type;
        },

        getType: function() {
            return this.options.type;
        },

        getGridConfig: function(table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function(i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function(options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        bindEvent: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');

            /*
             * 绑定时间
             *
             */
            //$.datepicker.setDefaults( $.datepicker.regional[ "" ] );

            $container.find("#StartTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#EndTime").datepicker("option", "minDate", selectedDate);
                }

            });

            $container.find("#EndTime").datetimepicker({
                onClose: function(selectedDate) {
                    $("#StartTime").datepicker("option", "maxDate", selectedDate);
                }
            });

            $form.find('button[type="reset"]').click(function() {
                self.resetQueryForm();
            });
        },

        resetQueryForm: function() {
            var self = this;
            var $container = this.options.$container;
            var $form = $container.find('form[name="basicFrm"]');
            // 从suggest获得的数据都需要清空
            $form.find('input[data-key]').removeAttr('data-id');
        },

        reload: function(params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        },

        // 基本数据请求队列
        ajaxBasicRequestQueue: (function() {
            var Queue = [];

            var pushData = function(obj) {
                Queue.push(obj);
            };
            var getQueueLen = function() {
                return Queue.length;
            };
            var getQueueData = function() {
                return Queue;
            };
            var clearQueueData = function() {
                Queue = [];
            };

            return {
                pushData: pushData,
                getQueueLen: getQueueLen,
                getQueueData: getQueueData,
                clearQueueData: clearQueueData
            };

        })(),

        ajaxBasicRequestLen: -1,
        intverId: null,

        // 处理请求队列
        ajaxBasicRequestManage: (function() {

            var self = null,
                fct = null,
                tryNumbers = 10000; //尝试10000次

            var init = function(obj, func) {
                self = obj;
                fct = func;
                start();
            };

            var start = function() {
                var len = self.ajaxBasicRequestQueue.getQueueLen();
                if (len === 0) return;

                if (self.ajaxBasicRequestLen == len || tryNumbers == 1) {
                    clearInterval(self.intverId);
                    fct(self);
                    self.ajaxBasicRequestQueue.clearQueueData();
                } else if (self.ajaxBasicRequestLen != -1) {
                    return;
                } else {
                    var queue = self.ajaxBasicRequestQueue.getQueueData();
                    self.ajaxBasicRequestLen = 0;

                    $.each(queue, function(i, item) {
                        item.func(function() {
                            self.ajaxBasicRequestLen++;
                        });
                    });
                    self.intverId = setInterval(start, 10);
                }
                tryNumbers--;
            };
            return {
                init: init
            };
        })(),
    });

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
define(
    '../ancestor/Ancestor.Dao',['require','exports','module'],function(require, exports, module) {

        Ancestor.Dao = (function() {
            var config = Ancestor.Config;

            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // 获取配频道配置数据
            var getType = function(data, callback) {
                var options = {
                    url: config.CONFIGS_API.url,
                    dataType: 'json',
                    data: data,
                    method: 'get',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/configs");

            };

            var getSuggestData = function(url, data, callback) {

                var request = {};
                request.url = url;
                request.type = 'get';

                if (data.needCookie)
                    request.needCookie = true;

                request.params = data;

                data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, '/redirect');
            };

            var getQipuDataById = function(item, callback) {
                var url = Ancestor.Config.QIPU_URL.replace("${QIPUID}", item.qipuId);

                var request = {};
                request.url = url;
                request.type = 'get';

                var data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    method: 'post',
                    data: data,
                    success: function(data) {
                        callback.call(this, data, item);
                    },
                    error: function(data) {
                        callback.call(this, data, item);
                    }
                };

                ajax(options, '/redirect');
            };

            // 获取分类
            var getuniversalCodeData = function(url, data, callback) {

                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, url.split('api')[1]);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var qichuanUploadFile = function(data, handler) {
                var self = this;
                var xhr = _getXHR();
                var precent = 0;
                xhr.open('POST', data.url, true);
                // xhr.setRequestHeader('Content-Type', 'multipart/form-data');
                for (var key in data.headers) {
                    xhr.setRequestHeader(key, data.headers[key]);
                }

                xhr.upload.onprogress = function(e) {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (e.lengthComputable) {
                        precent = (e.loaded / e.total) * 100;
                        if (handler.onProgress) {
                            handler.onProgress.apply(self, [precent, data]);
                        }
                    }
                };

                xhr.onreadystatechange = function() {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (xhr.readyState == 4) {
                        var stat = xhr.status;
                        if ((stat >= 200 && stat < 300) || stat == 304 || stat == 1223 || stat === 0) {
                            if (handler.onFinish) {
                                handler.onFinish.call(self, data);
                            }
                        } else {
                            if (handler.onFail) {
                                handler.onFail.call(self, data);
                            }
                        }
                    }
                };

                var formData = new FormData();
                formData.append('businessType', data.headers['businessType']);
                formData.append('fileid', data.headers['file_id']);
                formData.append('imagefile', data.file);

                // xhr.send(data.file || null);
                xhr.send(formData);


                return xhr;
            };


            var qichuanRequestFile = function(options, callback) {
                options = options || {};
                var headers = options.headers || {};

                var options = {
                    url: options.url + '?t=' + new Date().getTime(),
                    // url: options.url,
                    dataType: 'json',
                    // data: data,
                    headers: headers,
                    method: 'get',
                    success: function(data) {
                        if (data && data.code == 'A00000') {
                            callback.call(this, data);
                        } else {
                            console.log('get access fail.');
                            callback.call(this, data);
                        }
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, false);

            };

            var platSettings = function(options, callback) {
                var options = {
                    url: '/api/channel/getPlatSettings',
                    dataType: 'json',
                    data: options,
                    method: 'post',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/channel/getPlatSettings");
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                getType: getType,
                qichuanRequestFile: qichuanRequestFile,
                qichuanUploadFile: qichuanUploadFile,
                getSuggestData: getSuggestData,
                platSettings: platSettings,
                getuniversalCodeData: getuniversalCodeData,
                getQipuDataById: getQipuDataById,
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Upload.js
 * @path:   js-src/upload/
 * @desc:   基于HTML5的上传的核心组件，基于奇传的接口
 *
 * @author: lichunping@qiyi.com
 * @date:   2013-05-15
 *
 */
define('../ancestor/Ancestor.Upload',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/

    Ancestor.Upload = function(options) {
        this.dao = Ancestor.Dao;
        this.config = Ancestor.Config;
        options = options || {};

        this.options = $.extend(true, {

            // 如果想支持想支持多文件需在外再封装一层
            file: null,

            uploadHost: null,
            // finishUrl: '/upload',
            // cancelUrl: '/cancelupload',

            requestURL: this.config.QICHUAN.image_requestURL_test,
            uploadURL: this.config.QICHUAN.image_uploadURL_test,

            deviceId: this.config.QICHUAN.deviceId,

            // 开始时间
            startTime: 0,

            role: 'epg_image',
            businessType: 'image',
            producttype: 'ppc',

            // spath: null,
            currentDate: null,
            // openAuthInfo: null,

            // 请求文件完成
            onRequest: function(data) {},
            // 开始发送数据
            onStart: function(data) {},
            // 上传成功
            onFinish: function(data) {},
            // 上传暂停
            onPause: function(data) {},
            // 上传恢复
            onResume: function(data) {},
            // 上传过程回调，每个分片
            onProgress: function(data) {},
            // 取消上传
            onCancel: function(data) {},
            // 上传失败
            onFail: function(data) {},
            // 上传出现错误
            onError: function(data) {}

        }, options);

        // 模拟构造方法，在实例化执行
        // 根据自己的需要加入需要初始化执行的内容
        this.construct = options.construct || function() {
            this.init();
        };

        // 放在最下方立即执行
        this.construct.call(this);
    };

    Ancestor.Upload.prototype = {

        init: function() {
            var self = this;
            var _options = self.options;

            /*
            var isNormalUser = User.Util.isNormal();
            if(!_options.uploadURL) {
                if(isNormalUser) {
                    _options.uploadURL = this.config.QICHUAN.image_uploadURL;
                } else {
                    _options.uploadURL = this.config.QICHUAN.inner_image_uploadURL;
                }
            }
            */
        },

        /**
         * 用于更新options内容，继承选项，覆盖相同属性
         * @param {Object} options  选项
         */
        update: function(options) {
            this.options = $.extend(true, this.options, options);
        },

        getUID: function() {
            return Com.string.createUUID();
        },

        getFile: function() {
            return this.options.file;
        },

        getUploadHost: function(url) {
            var self = this;
            if (this.uploadHost) {
                return this.uploadHost;
            }
            url = url || self.options.uploadUrl;
            if (!url || url.length <= 0) {
                return null;
            }
            // 含http://, 不是 Com.url.host(url);
            return url.substr(0, url.lastIndexOf('/'));
        },

        getFileType: function(name) {
            return Com.file.getFileType(name);
        },


        getDeviceId: function() {
            return this.options.deviceId;
        },

        getFilePath: function() {
            return this.options.role + this.options.spath;
        },


        getRequestFileOptions: function(options) {
            var self = this;
            var _options = self.options;
            options = options || {};
            var file = options.file || self.getFile();
            var currentDate = _options.currentDate || Com.date.getCurrentDate();
            var openAuthInfo = options.openAuthInfo || {};
            var access_token = openAuthInfo.access_token || self.getAccessToken();
            var fileUID = file.uid || self.getUID();

            // must be required the file info, authorize info
            if (!file.size || !access_token) {
                console.log('is not file or access_token.');
                return null;
            }

            options = {
                role: options.role || _options.role,
                // 奇传改为2.0后，请求file时不再传递spath
                // spath: options.spath ||  ( currentDate + '/' + fileUID
                //         + '.' + Com.file.getExt(file.name) ),
                spath: options.spath,
                filesize: file.size,
                filetype: Com.file.getExt(file.name),
                access_token: access_token
            };

            return options;
        },

        /*
        options = {
            url: requestURL, // optional
            data: {
                role: 角色,  // optional
                access_token: 认证, // optional
                filesize: 文件尺寸, // required
                spath: 文件存储路径, // optional
                device_id: 客户端UID // optional
            }
        }
        */
        requestFile: function(options, callback) {
            var self = this;
            var _options = self.options;
            options = options || {};

            var params = {
                url: options.url || _options.requestURL,
                headers: {
                    filetype: Com.file.getExt(options.file.name),
                    filesize: options.file.size,
                    role: options.file.role || _options.role,
                    location: options.file.location || _options.location,
                    producttype: options.file.producttype || _options.producttype,
                    businessType: options.file.businessType || _options.businessType
                }
            };

            var _callback = function(data) {
                if (data && data.code == 'A00000') {
                    callback.call(this, data);
                } else {
                    _options.onError.call(self, data);
                }
                if (_options.onRequest) {
                    _options.onRequest.call(self, data);
                }
            };

            return self.dao.qichuanRequestFile(params, _callback);
        },

        send: function(options, handler) {
            //        var self = this;
            handler = handler || {};
            var $xhr = $.ajax({
                url: options.url,
                processData: false,
                dataType: 'json',
                headers: options.headers,
                contentType: 'application/x-www-form-urlencoded',
                // contentType: false,
                data: options.file,
                method: 'POST',

                beforeSend: function(data) {
                    if (handler.onBeforeSend) {
                        handler.onBeforeSend.call(this, data);
                    }
                },
                success: function(data) {
                    if (handler.onFinish) {
                        handler.onFinish.call(this, data);
                    }
                },
                complete: function(data) {
                    if (handler.onComplete) {
                        handler.onComplete.call(this, data);
                    }
                },
                error: function(data) {
                    if (handler.onError) {
                        handler.onError.call(this, data);
                    }
                }
            });

            return $xhr;
        },



        uploadFile: function(options, callback) {

            var self = this;
            var _options = self.options;
            options = options || {};

            var data = options.data;

            var file = _options.file || self.getFile();
            var params;
            var handler = {
                onFail: _options.onFail,
                onError: _options.onError,
                onProgress: _options.onProgress
            };

            file.file_id = data.file_id;

            params = {
                url: file.upload_url || _options.uploadURL,
                file: file,
                headers: {
                    file_id: file.file_id,
                    file_size: file.size,
                    range: data.range || ('0' + '-' + (file.size - 1) + ''),
                    businessType: _options.businessType
                }
            };

            // 直接上传，完成后回调
            handler.onFinish = function(data) {

                if (!$.isPlainObject(data)) {
                    data = $.parseJSON(data);
                }
                if (data.code == 'A00000') {
                    _options.onFinish.call(self, data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            return self.dao.qichuanUploadFile(params, handler);
        },

        // 一个文件的片段上传完成后，发起结束通知
        finishUpload: function(options, handler) {
            var self = this;
            handler = handler || {};
            options = options || {};
            var _options = self.options;
            var file = options.file || self.getFile();
            var params = null;
            var access_token = options.access_token || self.getAccessToken();
            params = {
                contentType: 'application/json',
                url: options.url,
                headers: {
                    access_token: access_token,
                    file_id: file.file_id,
                    range_finished: 'true'
                }
            };

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onFinish.call(self, data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            self.send(params, {
                onFinish: callback
            });
        },

        startUpload: function(options, handler) {
            var self = this;
            var _options = self.options;
            options = options || {};

            handler = options.handler;

            if (options.file) {
                _options.file = options.file;
            }

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onStart.call(self, data);
                    self.uploadFile(data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            self.requestFile(options, callback);

        },

        cancelUpload: function(options) {
            var self = this;
            var _options = self.options;
            handler = handler || {};
            var file = options.file || _options.file;
            var cancelUrl = self.getUploadHost() + '' + _options.cancelUrl;
            var params = {
                url: cancelUrl,
                headers: {
                    // 按照奇传接口定义取消参数
                    access_token: options.access_token || self.getAccessToken(),
                    file_id: file.file_id,
                    status: 2
                }
            };

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onCancel.call(self, data);
                } else {
                    data.errorMsg = 'onCancel error.';
                    _options.onCancel.call(self, data);
                }
            };

            self.send(params, {
                onFinish: callback
            });

        }
    };


});

define(
    '../epg2/EpgWeb',['require','exports','module'],function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);
define(
    '../epg2/EpgWeb.Util',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Util = $.extend(true, {}, Ancestor.Util, {
            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },
            makeUpRedirect: function (url, method, params, needCookie) {
                var requestData = {url: url, type: method, params: params};
                if (needCookie === true) {
                    requestData.needCookie = true;
                }
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            quickDateFormat: function (startTime) {
                return startTime.getFullYear() + "-" +
                    (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                    (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
            },
            bindDateMax: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },
            setZeroTime: function (checkTime) {
                checkTime.setSeconds(0);
                checkTime.setMinutes(0);
                checkTime.setHours(0);
                checkTime.setMilliseconds(0);
            },
            setDayLastTime: function (checkTime) {
                checkTime.setSeconds(59);
                checkTime.setMinutes(59);
                checkTime.setHours(23);
                checkTime.setMilliseconds(0);
            },

            bindDate: function (nameMin, nameMax, plusData) {
                var options1 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                }
                var options2 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                }
                if (plusData != null && plusData.hasOwnProperty("slider")) {
                    options1.controlType = "slider";
                    options2.controlType = "slider";
                }
                $("input[name=" + nameMin + "]").datetimepicker(options1)
                $("input[name=" + nameMax + "]").datetimepicker(options2)
                if (plusData != null) {
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },



            bindDateMin: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                }
            },
            createPageBean: function () {
                return (function () {
                    var source = [];
                    var dataLength = source.length;
                    var rowNum = 10;
                    var total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    var cur = 1;

                    function goToFirst() {
                        return goToUser(1);
                    }

                    function goToLast() {
                        return goToUser(total);
                    }

                    function goToUser(toPage) {
                        if (toPage < 1) toPage = 1;
                        if (toPage > total) toPage = total;
                        cur = toPage;
                        var end = cur * rowNum > dataLength ? dataLength : cur * rowNum;
                        var showData = source.slice((cur - 1) * rowNum, end);
                        return {"total": total, "page": cur, "records": dataLength, "rows": showData};
                    }

                    function getCur() {
                        return goToUser(cur);
                    }

                    function goNext() {
                        return goToUser(cur + 1);
                    }

                    function goPrev() {
                        return goToUser(cur - 1);
                    }

                    function setNewData(newData, newRowNum) {
                        source = newData == null ? [] : newData;
                        if (newRowNum != null && newRowNum > 0) {
                            rowNum = newRowNum;
                        }
                        dataLength = source.length;
                        total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    }

                    function addNewOne(newOne) {
                        source.push(newOne);
                        setNewData(source, rowNum);
                    }

                    function delOne(delOne) {
                        var targetIndex = source.indexOf(delOne);
                        if (targetIndex > -1) {
                            source.splice(targetIndex, 1);
                            setNewData(source, rowNum);
                        }
                    }

                    function getSource() {
                        return [].concat(source);
                    }

                    function findData(keyName, value) {
                        var ret = null;
                        if (value == null || keyName == null) {
                            return null;
                        }
                        $.each(source, function (i, element) {
                            if (element != null && element[keyName] == value) {
                                ret = element;
                                return true;
                            }
                        })
                        return ret;
                    }

                    function sortData(func) {
                        if (typeof( func ) == "function") {
                            source.sort(func);
                        }
                    }

                    return {
                        goToFirst: goToFirst,
                        goToLast: goToLast,
                        goToUser: goToUser,
                        goNext: goNext,
                        goPrev: goPrev,
                        getCur: getCur,
                        setNewData: setNewData,
                        addNewOne: addNewOne,
                        delOne: delOne,
                        getSource: getSource,
                        findData: findData,
                        sortData: sortData
                    }
                })()
            },
            pageBeanPageHandler: function (gridId, pageId, pageBean, pgButton) {
                var retValue = null;
                switch (pgButton) {
                    case "next_" + pageId:
                        retValue = pageBean.goNext()
                        break;
                    case "prev_" + pageId:
                        retValue = pageBean.goPrev()
                        break;
                    case "last_" + pageId:
                        retValue = pageBean.goToLast()
                        break;
                    case "user":
                        retValue = pageBean.goToUser(parseInt($("#gbox_" + gridId + " .ui-pg-input").val()));
                        break;
                    case "first_" + pageId:
                        retValue = pageBean.goToFirst();
                        break;
                }
                return retValue
            },
            transGetParams: function (params) {
                var str = "";
                for (var key in params) {
                    str += key + "=" + params[key] + "&";
                }
                if (str.length > 0) {
                    str = str.substr(0, str.length - 1);
                }
                return str;
            },

            formatDateTimeFormat: function (myDate) {
                var year = myDate.getFullYear();
                var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
                var day = ("0" + myDate.getDate()).slice(-2);
                var h = ("0" + myDate.getHours()).slice(-2);
                var m = ("0" + myDate.getMinutes()).slice(-2);
                var s = ("0" + myDate.getSeconds()).slice(-2);
                return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
            },
            getQueryComponent: function (handlerObj) {
                return {
                    source: null,
                    total: 0,
                    completeNum: 0,
                    handlerObj: handlerObj,
                    doInit: function (newArr) {
                        var self = this;
                        self.source = newArr;
                        self.total = newArr.length;
                        self.completeNum = 0;
                        self.doSubmit();
                    },
                    doSubmit: function () {
                        var self = this;
                        self.doBefore();
                        $.each(self.source, function (i, element) {
                            self.doSingle(element, function () {
                                self.notifyHandler()
                            });
                        })
                    },
                    doBefore: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doBefore")) {
                                self.handlerObj.doBefore();
                            }
                        }
                    },
                    doAfter: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doAfter")) {
                                self.handlerObj.doAfter();
                            }
                        }
                    },
                    doSingle: function (element, notifyHandler) {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doSingle")) {
                                self.handlerObj.doSingle(element, notifyHandler);
                            }
                        }
                    },
                    notifyHandler: function () {
                        var self = this;
                        self.completeNum++;
                        if (self.completeNum == self.total) {
                            self.doAfter();
                        }
                    }
                };
            },
            createWeekManager: function (labelArr) {
                return (function ($labelArr) {
                    var focusStartTime = null;
                    var selectDateTime = null;
                    var weekday = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");

                    function preWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
                        }
                    }

                    function nextWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
                        }
                    }

                    function updateWeek(startTime) {
                        if (startTime != null) {
                            focusStartTime = startTime;
                        }
                        var tempStartTime = new Date(focusStartTime.getTime());
                        $labelArr.each(function (i, element) {
                            var lDateFormat = EpgWeb.Util.quickDateFormat(tempStartTime);
                            $(element).attr("query-date", lDateFormat);
                            $(element).removeClass("selected");
                            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
                            if (lDateFormat == selectDateTime) {
                                $(element).addClass("selected");
                            }
                            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
                        })
                    }

                    function quickToCurrentWeek() {
                        var current = new Date();
                        var currentIndex = -1;
                        if (current.getDay() == 0) {
                            currentIndex = 6;
                        } else {
                            currentIndex = current.getDay() - 1;
                        }
                        selectDateTime = EpgWeb.Util.quickDateFormat(current)
                        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
                        //updateTableByDate(selectDateTime);
                        return selectDateTime;
                    }

                    return{
                        preWeek: preWeek,
                        nextWeek: nextWeek,
                        quickToCurrentWeek: quickToCurrentWeek
                    }
                })(labelArr)
            },
            createHeartBeatUtil: function () {
                return  (function () {
                    var params = {
                        startTime: 0,
                        isStarted: false,
                        indexId: 0,
                        dataArr: []
                    }

                    function doHeartBeat() {
                        var curTime = Date.now();
                        var cpArr = [].concat(params.dataArr);

                        $.each(cpArr, function (i, element) {
                            tick(element, curTime);
                        })
                    }

                    function start() {
                        if (params.isStarted) {
                            console.log("has started");
                            return;
                        }
                        params.startTime = Date.now();
                        params.isStarted = true;
                        $.each(params.dataArr, function (i, elment) {
                            elment.lastTime = params.startTime;
                        })
                        setInterval(function () {
                            doHeartBeat();
                        }, 160)
                    }

                    function tick(element, curTime) {
                        if (element.block || element.stop) {
                            return;
                        }
                        if (element.lastTime + element.gapTime < curTime) {
                            element.lastTime = curTime;
                            element.options.handler();
                            if (element.options.needBlock) {
                                element.block = true;
                            }
                        }
                    }

                    function pushTask(taskObj) {
                        params.indexId++;
                        var taskOptions = {
                            block: false,
                            stop: taskObj.stop || false,
                            options: taskObj,
                            id: params.indexId,
                            lastTime: 0
                        }
                        taskOptions.gapTime = accountGapTime(taskObj)
                        if (params.isStarted) {
                            taskOptions.lastTime = Date.now() + 100;
                        }
                        params.dataArr.push(taskOptions);
                        return taskOptions;
                    }

                    function accountGapTime(taskObj) {
                        var time = [0, 0, 0, 0];//ms,s,m,h
                        if ("ms" in taskObj.gap) {
                            time[0] = taskObj.gap.ms;
                        }
                        if ("s" in taskObj.gap) {
                            time[1] = taskObj.gap.s;
                        }
                        if ("m" in taskObj.gap) {
                            time[2] = taskObj.gap.m;
                        }
                        if ("h" in taskObj.gap) {
                            time[3] = taskObj.gap.h;
                        }
                        return  time[0] + time[1] * 1000 + time[2] * 60000 + time[3] * 3600000;
                    }

                    return {
                        start: start,
                        doHeartBeat: doHeartBeat,
                        pushTask: pushTask,
                        tick: tick
                    }
                })();
            },
            notifyAlert: function (sendData, handler) {
                EpgWeb.Dao.notifyAlert(sendData, function (rdata) {
                    handler(rdata)
                });
            },
            getCurrentUserEntity:function(){
                var ret = null;
                try{
                    ret =auth.baseInfo.authInfo;
                }catch (e){
                    console.warn(e);
                }
                return ret
            }
        });
    }
);
define(
    '../epg2/EpgWeb.Plugin',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Plugin = {
            showTips: function (options) {
                if (!options.hasOwnProperty("type")) {
                    options.type = "success";
                }
                if ($(document).tips != null) {
                    $(document).tips(options)
                }
                if ($(document).tip != null) {
                    $(document).tip(options)
                } else {
                    console.log("no tips plugin " + options);
                }
            },
            Validate: (function () {
                var reg1 = /^\d+$/;
                var reg3 = /^[1-9]\d*$/;
                var reg2 = /^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) ([0-2][0-9]):([0-5][0-9]):([0-5][0-9])$/;
                var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
//                var _defaultHandler = function(msg){
//                    EpgWeb.Plugin.showTips({type: "error", content: msg})
//                }
                var _bindHandler = null;
                var checkObj = {
                    self_design: function (checkData, checkValue) {
                        return checkData.checkCall(checkData, checkValue)
                    },
                    date: function (checkData, checkValue) {
                        return checkDateFormat(checkValue);
                    },
                    not_empty: function (checkData, checkValue) {
                        return checkValue != null && $.trim(checkValue).length > 0;
                    },
                    eq: function (checkData, checkValue) {
                        return checkValue === checkData.other;
                    },
                    ne: function (checkData, checkValue) {
                        return checkValue !== checkData.other;
                    },
                    ge: function (checkData, checkValue) {
                        return  checkValue >= checkData.other;
                    },
                    gt: function (checkData, checkValue) {
                        return  checkValue > checkData.other;
                    },
                    lt: function (checkData, checkValue) {
                        return checkValue < checkData.other;
                    },
                    le: function (checkData, checkValue) {
                        return checkValue <= checkData.other;
                    },
                    positive:function(checkData, checkValue) {
                        return  checkPositive(checkValue)
                    },
                    number: function (checkData, checkValue) {
                        return checkNum(checkValue);
                    },
                    endsWith: function (checkData, checkValue) {
                        return checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                    }
                }

                function checkNum(checkString) {
                    return reg1.test(checkString)
                }

                function checkDateFormat(checkString) {
                    return reg2.test(checkString)
                }

                function checkPositive(checkString) {
                    return reg3.test(checkString)
                }

                function defaultHandler(msg) {
                    if(_bindHandler != null){
                        _bindHandler(msg);
                    }
                }

                function batchCheck(checkArr) {
                    if (checkArr == null) {
                        checkArr = [];
                    }
                    if (checkArr.length == 0) {
                        return true;
                    }
                    var flag = false;
                    $.each(checkArr, function (index, checkData) {
                        flag = baseCheck(checkData);
                        if (!flag) {
                            return false;
                        }
                    })
                    return flag;
                }

                function baseCheck(checkData) {
                    var flag = false;
                    //$.isArray(checkData.value )
                    if (!(checkData.value instanceof Array)) {
                        checkData.value = [checkData.value];
                    }
                    //$.isArray(checkData.error )
                    if (!(checkData.error instanceof Array)) {
                        checkData.error = [checkData.error];
                    }
                    if (checkData.handler == null) {
                        checkData.handler = defaultHandler;
                    }
                    $.each(checkData.value, function (index, checkValue) {
                        if (checkObj.hasOwnProperty(checkData.type)) {
                            flag = checkObj[checkData.type](checkData, checkValue);
                        }
                        if (!flag) {
                            var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                            checkData.handler(hint);
                            return false;
                        }
                    })
                    return flag
                }
                function bindDefaultHandler(func){
                    _bindHandler = func;
                }
                return {
                    baseCheck: baseCheck,
                    batchCheck: batchCheck,
                    checkDateFormat: checkDateFormat,
                    checkNum: checkNum,
                    bindDefaultHandler:bindDefaultHandler
                }
            })(),

            tableToExcel: (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g,
                            function (m, p) {
                                return c[p];
                            })
                    };

                return function (table, name) {
                    if (!table.nodeType) table = document.getElementById(table)
                    var ctx = {
                        worksheet: name || 'Worksheet',
                        table: table.innerHTML
                    }
                    window.location.href = uri + base64(format(template, ctx))
                }
            })()
        };

    }
);
define(
    '../epg2/EpgWeb.Dao',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Dao = $.extend({}, Ancestor.Dao, {
            cfgName: {
                LiveType: "LiveType",
                LogType: "LogType",
                episodeGradeType: "EpisodeGradeType",
                liveProgramType: "LiveProgramType",
                liveChannelType: "LiveChannelType",
                getChannel: "getChannel"
            },
            channelId: null,
            getDataByName: function (targetName) {
                var responseData = EpgWeb.ajaxQueue.findResponseData(targetName);
                return responseData;
            },
            sendAjax: function (url, method, data, callback, authUrl) {
                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    type: method,
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                };
                Ancestor.Dao.ajax(options, authUrl);
            },
            appendAuthUrl: function (options, authUrl) {
                options = $.extend({},options, {
                    beforeSend: function (request) {
                        var authBase = Ancestor.Util.getAuth('/vod/episodeLogList');
                        request.setRequestHeader('Sign', authBase.sign);
                        request.setRequestHeader("Time", authBase.clientTime);
                        request.setRequestHeader("From", authBase.from);
                        request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                    }
                })
                return options;
            },

            sendProxy: function (options, headers) {
                $.ajax(this.transToProxyOptions(options, headers));
            },
            transToProxyOptions: function (options, headers) {
                var requestData = {url: options.url, type: options.type, params: options.data, needCookie: true};
                if (headers != null) {
                    requestData.headers = headers;
                }
                var newOptions = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    timeout: options.timeout?options.timeout: 5000,
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        options.success(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        options.error(null);
                    }
                }
                return newOptions;
            },
            doGet: function (url, data, callback) {
                var dataArr = [];
                for (var key in data) {
                    dataArr.push(key + "=" + data[key]);
                }

                var options = {
                    url: url,
                    dataType: 'json',
                    data: dataArr.join("&"),
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                $.ajax(options);
            },
            doAuthData: function (handlerObj) {
                if (auth == null) {
                    auth = Ancestor.Auth;
                }
                auth.getAuthData({tips: 1, url: handlerObj.url}, function (rt) {
                    if (rt == null) {
                        if (handlerObj.hasOwnProperty("doSuccess")) {
                            handlerObj.doSuccess();
                        }
                    } else {
                        if (handlerObj.hasOwnProperty("doError")) {
                            handlerObj.doError();
                        }
                    }
                    if (handlerObj.hasOwnProperty("doFinal")) {
                        handlerObj.doFinal();
                    }
                });
            },
//            checkJSVersion: function (data, callback) {
//                //method, data, callback, authUrl) {
//                this.sendAjax("/api/version/check", "post", {data:JSON.stringify(data)}, callback);
//            }
            notifyAlert: function (sendData, callback) {
                var url = EpgWeb.urlConfig.notifyAlertUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(sendData)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/notify/alertPlatform");
            }

        })
    }
);
define(
    '../epg2/EpgWeb.Task',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: EpgWeb.urlConfig.configs,
                        dataType: "json",
                        data: {type: typeName},
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            var getChannel = function (regName,params) {
                return {
                    regName:regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: params
                    }
                }
            }
            return {
                getConfigType: getConfigType,
                getChannel:getChannel
            }
        })()
    }
);
define(
    '../epg2/EpgWeb.PingBack',['require','exports','module'],function (require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };


// [步骤名称 操作结果] [entityId=节目Id][msg=任意消息][stepInfo={json对象，用于携带其它信息}][cost=步骤执行耗时，可选]
        EpgWeb.PingBack = {
            PARAM_TYPE:{
                append_submit:402,
                normal_submit:403
            },
            typeArr: ["create_video", "submit_format"],
            doFoldList: function (originalData) {
                var retValue = originalData;
                try {
                    var newData = JSON.parse(retValue);
                    if (newData.list != null) {
                        newData.list = JSON.parse(newData.list)
                        var newFold = [];
                        var nodeStart = -100;
                        var nodeEnd = -100;
                        var curIndex = 0;
                        $.each(newData.list, function (i, element) {
                            curIndex = element;
                            if (curIndex > nodeEnd + 1) {
                                if (nodeStart >= 0) {
                                    newFold.push({ start: nodeStart, end: nodeEnd});
                                }
                                nodeStart = curIndex;
                                nodeEnd = curIndex;
                            } else if (curIndex == nodeEnd + 1) {
                                nodeEnd = curIndex;
                            }
                        })
                        if (nodeEnd >= nodeStart) {
                            newFold.push({ start: nodeStart, end: nodeEnd});
                        }
                        newData.list = newFold;
                        retValue = JSON.stringify(newData);
                    }
                } catch (e) {
                    console.log("error", e);
                }
                return retValue
            },
            transFormatData: function (wrapData) {
                var ret = {};
                ret.success = wrapData.success;
                if (wrapData.success == true) {
                    ret.successLogExpression = "[" + wrapData.funcType + " success]";
                } else {
                    ret.failLogExpression = "[" + wrapData.funcType + " error]";
                }
                ret.detail = "[entityId=" + wrapData.programId + "][stepInfo=" + this.doFoldList(wrapData.sendData) + "][plusMsg=" + wrapData.plusMsg + "]";
                wrapData.sendData = null;
                ret.keyId = "" + wrapData.programId;
                ret.serverIp = "" + wrapData.serverIp;
                ret.relationData = [
                    {description: "奇谱", columnName: "programId", "columnValue": "" + wrapData.programId, "isQueryParam": "0", "isQueryList": "1"}
                ];
                ret.paramType = wrapData.paramType ?  wrapData.paramType:this.PARAM_TYPE.append_submit;
                return  ret
            },
            doExecute: function (wrapData, callback) {
                var testUrl = "http://xiu-test-monitor-dev001-cqdx.qiyi.virtual/monitor-api/pingback/flow";
                var onlineUrl = "http://monitor.live.qiyi.domain/monitor-api/pingback/flow";
                var paramsArr = [];
                var retData = this.transFormatData(wrapData);
                paramsArr.push({keyName: "business", value: "live2vod"});
                paramsArr.push({keyName: "paramType", value: retData.paramType })
                if (retData.success) {
                    paramsArr.push({keyName: "successLogExpression", value: retData.successLogExpression})
                } else {
                    paramsArr.push({keyName: "failLogExpression", value: retData.failLogExpression})
                }
                paramsArr.push({keyName: "sendTime", value: new Date().getTime() })
                paramsArr.push({keyName: "detail", value: retData.detail});
                paramsArr.push({keyName: "keyId", value: retData.keyId})
                paramsArr.push({keyName: "serverIp", value: retData.serverIp}) //
                paramsArr.push({keyName: "relationData", value: retData.relationData})
                paramsArr.push({keyName: "checkToken", value: md5("business=live2vod|F@(LhCw79plfWd3$83#530")})

                var sendData = {}
                $.each(paramsArr, function (index, element) {
                    if (element.value != null) {
                        sendData[element.keyName] = element.value;
                    }
                })

                for (var key in wrapData) {
                    if(wrapData[key] != null){
                        sendData[key] = wrapData[key];
                    }
                }
                var options = {
                    url: auth.dev() ? testUrl : onlineUrl,
                    dataType: 'json',
                    data: sendData,
                    type: "post",
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                }
                EpgWeb.Dao.sendProxy(options)
            },
            doQuickSend: function (wrapData) {
                this.doExecute(wrapData, function (data) {
                    console.log(data);
                })
            }
        }
    }
);
define(
    '../epg2/EpgWeb.PingBackCost',['require','exports','module'],function (require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };
//        business	业务名称	业务代码：PGC，CPP等	Y	string
//        name	服务名称	该服务名称需要和你在监控中所配置的名称一致	Y	string
//        cost	耗时	单位是毫秒	Y	sring	1000
//        sendTime	投递数据的时间戳	投递数据的时间戳（到秒一级）	Y	string	1493258494
//        detail	透传详细信息	想要传递过来的详细信息，如一条完整日志	N	json string
//        serverIp	机器IP地址	产生投递信息的机器IP	Y	string
//        checkToken	接口签名参数	接口签名参数	Y	string
        EpgWeb.PingBackCost = {
            doExecute: function (wrapData, callback) {
                var testUrl = "http://xiu-test-monitor-dev001-cqdx.qiyi.virtual/monitor-api/pingback/cost";
                var onlineUrl = "http://monitor.live.qiyi.domain/monitor-api/pingback/cost";
                var paramsArr = [];
                var retData = wrapData;
                paramsArr.push({keyName: "business", value: "live2vod"});
                paramsArr.push({keyName: "name", value: "zzd_jqh"});
                paramsArr.push({keyName: "cost", value: retData.costTime + ""});
                paramsArr.push({keyName: "sendTime", value: parseInt(new Date().getTime() / 1000 )  })
                paramsArr.push({keyName: "detail", value: retData.detail});
                paramsArr.push({keyName: "serverIp", value: retData.serverIp}) //
                paramsArr.push({keyName: "checkToken", value: md5("business=live2vod|F@(LhCw79plfWd3$83#530")})

                var sendData = {}
                $.each(paramsArr, function (index, element) {
                    if (element.value != null) {
                        sendData[element.keyName] = element.value;
                    }
                })
                var options = {
                    url: auth.dev() ? testUrl : onlineUrl,
                    dataType: 'json',
                    data: sendData,
                    type: "post",
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                }
                EpgWeb.Dao.sendProxy(options)
            },
            doQuickSend: function (wrapData) {
                this.doExecute(wrapData, function (data) {
                    console.log(data);
                })
            },
            doTest: function (enterData) {
                var demo = $.extend({}, enterData, { costTime: 30000, serverIp: "127.0.0.1", detail: JSON.stringify({msg: "demo"})})
                this.doQuickSend(demo)
            }
        }
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../program/Program',['require','exports','module'],function (require, exports, module) {
        window.Program = window.Program || {
            version: '1.0'
        };
        Program.Constant = {
            daoju_inner_url: "http://admin.vienx.qiyi.domain/api/partner/query.json",
            vote_inner_url: "http://vote.i.iqiyi.com/eagle/runman/query_votes",
            vote_token: "qiyi-vote-api-token-howareyou-fine3q",
            daoju_secret: auth.dev() ? '123456798' : 'LZl$UX*7bb^TTTdH$33R',
            daoju_ip: auth.dev() ? '127.0.0.1' : '10.153.108.204',
            query_feed_url: "http://api.t.qiyi.domain/feed/admin/get_feeds_by_ids"
        }

    }
);
define(
    '../program/Program.Action',['require','exports','module'],function (require, exports, module) {
        Program.Action = (function () {
            // 表格
            var programListGrid = null;
            var programLibraryGrid = null;
            var editForm = null;
            // 节目单列表
            var listRun = function () {
                Ancestor.Config.EPG_AUTH.list = '/program/list';
                if (!programListGrid) {
                    programListGrid = new Program.Grid($.extend(true, {
                        // '$container': $('#ChannelListContainer'),
                        type: 0
                    }, {}));
                }
                programListGrid.runDayList();
                console.log('program grid run');
            }

            var libraryRun = function () {
                Ancestor.Config.EPG_AUTH.list = '/program/list';
                if (!programLibraryGrid) {
                    programLibraryGrid = new Program.Grid($.extend(true, {
                        '$container': $('#ProgramListContainer'),
                        $grid:$('#list'),
                        $feedGrid:$('#feedList'),
                        type: 0
                    }, {}));
                }
                programLibraryGrid.runLibrary();
                console.log('library grid run');
            }

            // 节目新建/编目
//            var editRun = function () {
//                if(editForm == null){
//                    editForm = new Program.Edit($.extend(true, {
//                       // '$form': $('form[role=form]')
//                    }, {}));
//                    editForm.init();
//                }
//                console.log(' editRun ');
//            }

            return {
                listRun: listRun,
                libraryRun: libraryRun
            }
        })();
    }
);
///import js-src/lib/
///import js-src/com/
define('../program/Program.Config',['require','exports','module'],function (require, exports, module) {
    Program.Config = $.extend({}, Ancestor.Config, {
        RECOMMEND_RATE: {
          "0": "不推荐", "1": "普通推荐", "2": "重点推荐", "3": "强烈推荐"
        },
        TABLE_COLMODEL_CONFIG: {
            qipuId: {
                name: "qipuId",
                index: 'qipuId',
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.qipuId(v, o, r);
                }
            },
            pname: {
                name: "pname",
                index: 'pname',
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.pname(v, o, r);
                }
            },
            playStatus:{
                name: "playStatus",
                index: 'playStatus',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.playStatus(v, o, r);
                }
            },
            startPlayTime: {
                name: "startPlayTime",
                index: 'startPlayTime',
                title: false,
                width: 120,
                sortable: false,
                align: "center"
            },
            endPlayTime: {
                name: "endPlayTime",
                index: 'endPlayTime',
                title: false,
                width: 120,
                sortable: false,
                align: "center"
            },
            type: {
                name: "type",
                index: 'type',
                title: false,
                width: 100,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.type(v, o, r);
                }
            },
            bossStatus: {
                name: "bossStatus",
                index: 'bossStatus',
                title: false,
                width: 90,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.bossStatus(v, o, r);
                }
            },
            episodeGrade: {
                //wait to do
                index: "episodeGrade",
                name: "episodeGrade",
                title: false,
                width: 80,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.episodeGrade(v, o, r);
                }
            },
            channelName: {
                name: "channelName",
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.channelName(v, o, r);
                }
            },

            onlineStatus: {
                name: "onlineStatus",
                index: 'onlineStatus',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.onlineStatus(v, o, r);
                }
            },
            formal: {
                name: "formal",
                index: 'formal',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.formal(v, o, r);
                }
            },

            updateTime: {
                name: "updateTime",
                index: 'updateTime',
                title: false,
                width: 120,
                sortable: false,
                align: "center"
            },
            operate: {
                name: "operate",
                title: false,
                width: 180,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.operate(v, o, r);
                }
            },
            oaDocEditorStatus: {
                index: 'oaDocEditorStatus',
                name: "oaDocEditorStatus",
                title: false,
                width: 100,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.oaDocEditorStatus(v, o, r);
                }
            },

            operate2: {
                title: false,
                width: 150,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.operate2(v, o, r);
                }
            },
            recommendRate: {
                name: "recommendRate",
                index: 'recommendRate',
                title: false,
                width: 90,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.recommendRate(v, o, r);
                }
            },
            hot: {
                name: "hot",
                index: 'hot',
                title: false,
                width: 130,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.hot(v,o,r);
                }
            },
            test: {
                name: "test",
                index: 'test',
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function(v, o, r) {
                    return Program.Util.formatter.test(v,o,r);
                }
            },
            log_id: {
                name: 'id',
                index: 'id',
                title: false,
                sortable: false,
                hidden: true
            },
            log_addTime:{
                name: 'addTime',
                index: 'addTime',
                sortable: false,
                title: false,
                width: 150,
                align: 'center'
            },
            log_user: {
                name: 'user',
                index: 'user',
                sortable: false,
                title: false,
                width: 150
            },
            log_type: {
                name: 'type',
                index: 'type',
                sortable: false,
                title: false,
                width: 120,
                formatter: function (v, o, r) {
                    return Program.Util.formatter.log_type(v,o, r);
                }
            },
            log_descr: {
                name: "descr",
                index: 'descr',
                title: false,
                width: 450,
                sortable: false
            },
            //'feed_id', "feed_doc", "circle_name" , "event_name" , "uid","operator_user","publish_time"
            feed_id: {
                name: "feedId",
                index: 'feedId',
                title: false,
                width: 70,
                align: "center",
                sortable: false

            },
            feed_doc: {
                name: "description",
                index: 'description',
                title: false,
                width: 120,
                align: "center",
                sortable: false

            },
            circle_name: {
                name: "wallName",
                index: 'wallName',
                title: false,
                width: 200,
                align: "center",
                sortable: false
            },
            event_name: {
                name: "eventName",
                index: 'eventName',
                title: false,
                width: 120,
                sortable: false
            },
            uid: {
                name: "uid",
                index: 'uid',
                title: false,
                width: 70,
                align: "center",
                sortable: false
            },
            operator_user: {
                name: "name",
                index: 'name',
                title: false,
                width: 70,
                align: "center",
                sortable: false
            },
            publish_time: {
                name: "releaseDate",
                index: 'releaseDate',
                title: false,
                width: 120,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Program.Util.formatter.publish_time(v,o, r);
                }
            }
        },
        TABLE_LIBRARY: {
            url: EpgWeb.urlConfig.programList,
            loadBeforeSend: function (xhr, settings) {
                xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                return true;
            },
            rowNum: 40,
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            gridComplete: function () {
                Program.Util.checkPlaying();
            },
            multiselect: false,
            datatype: "local",
            loadtext: '加载中...',
            loadui: "block",
            mtype: "post",
            caption: "节目单列表",
            pager: "#pager",
            colNames: ["奇谱ID", "节目名称", "所属频道", "节目播放状态", "节目状态", "节目类型", "付费状态", "操作","OA审核状态", "节目等级",
                "开始时间", "结束时间", "推荐等级", "是否允许进入热门直播", "是否为测试数据", "是否正式流", "更新日期"],
            colModel: ['qipuId', 'pname', 'channelName', 'playStatus' , 'onlineStatus', 'type', 'bossStatus', "operate", "oaDocEditorStatus","episodeGrade",
                'startPlayTime', 'endPlayTime', "recommendRate", "hot", "test", "formal", 'updateTime']
        },
        TABLE_LIST: {
            url: EpgWeb.urlConfig.programList,
            loadBeforeSend: function (xhr, settings) {
                xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                return true;
            },
            loadComplete: function () {
                var jqGridTarget = $("#list");
                var re_records = jqGridTarget.getGridParam('records');
                var parentElement = jqGridTarget.parent();
                var norecordElement = parentElement.find(".norecords")
                if (re_records == 0 || re_records == null) {
                    if (norecordElement.html() == null) {
                        parentElement.append('<div class="norecords">没有符合数据</div>');
                        norecordElement.hide();
                    }
                    norecordElement.show();
                } else {
                    norecordElement.hide();
                }
            },
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            multiselect: false,
            mtype: "post",
            datatype: "local",
            height: 450,
            caption: "节目单列表",
            colNames: ["奇谱ID", "节目名称", "开始时间", "结束时间", "节目类型", "付费状态", "更新日期", "操作"],
            colModel: ["qipuId", "pname", "startPlayTime", "endPlayTime", "type", "bossStatus", "updateTime", "operate2"],
            pager: "#pager",
            toolbar: [true, "top"]
        },

        TABLE_LOG: {
            url: EpgWeb.urlConfig.programLog,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/program/loglist");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 50,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["ID", "操作时间", "人员", "动作", "备注"],
            colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
            pager: "#log_pager"
        },

        TABLE_FEED: {
            localReader: {
                id: "feedId",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            },
            multiselect: false,
            datatype: "local",
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 10,
            colNames: ["feedid", "feed文案", "落地圈子名称", "落地事件", "UID","发布人","发布时间"],
            colModel: ['feed_id', "feed_doc", "circle_name" , "event_name" , "uid","operator_user","publish_time"],
            pager: "#feed_pager",
            onPaging: function (pgButton) {
                var retValue = Program.Util.pageBeanPageHandler("feedList", "feed_pager", Program.Config.PageBeanFeed, pgButton);
                if (retValue != null) {
                    $("#feedList")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },

        WeekManager: null,
        dateTime: null,
        PageBeanFeed:null,
        AUTH_FORCE_CHECK: false,
        AUTH_FEED_VIEW:false,
        AUTH_LOG_DETAIL:false,
        oaTest:false,
        Header:{
            daojuSuggest:["道具渠道号","道具渠道名称","创建时间","创建人"],
            voteSuggest:["投票ID","投票名称","创建时间"],
            puyuSuggest:["条形码","片名","出品方","发行时间","主演 /演唱者","导演","版权方","合同编号","授权起止时间"],
            albumSuggest: ["奇谱ID","显示名称","频道","版权到期时间","是否付费","发布状态"],
            qitanSuggest:["评论ID","评论名称","创建时间"],
            actorSuggest:["人物ID","名称","别名","性别","人物类型","审核状态"],
            playbackSuggest:["节目Id","节目显示名称","频道","发行时间","是否付费","发布状态"]
        },
        EDIT_VALIDATOR: {
            rules: {
                pname:{
                    required:true,

                    maxlength:40
                }
            },
            messages:{

                pname:{
                    required:"节目名称不能为空",
                    maxlength:"节目名称长度不能超过{0}"
                }
            },
            onkeyup: function (element) {
                var $element = $(element);
                var name = $element.attr('name');
                var cb = {
                    onkeyup: true
                };

                if (typeof cb.onkeyup == 'function') {
                    cb.onkeyup($element, this);
                } else if (cb.onkeyup) {
                    $element.valid();
                }
            },
            onfocusout: function (element) {
                var $element = $(element);
                var name = $element.attr('name');
                var cb = {
                    onfocusout: true
                };

                if (typeof cb.onfocusout == 'function') {
                    cb.onfocusout($element, this);
                } else if (cb.onfocusout) {
                    $element.valid();
                }
            }
        }

    })


});
define(
    '../program/Program.Dao',['require','exports','module'],function (require, exports, module) {
        Program.Dao = $.extend({}, EpgWeb.Dao, {
            //获取 oa 工单数据
            readOaStatus:function(data, callback){
                var oa_test_url = "http://oa-trunktest.qiyi.domain/api/live/getLiveDetailsForEpg";
                var oa_online_url = "http://home.qiyi.domain/api/live/getLiveDetailsForEpg";
                var options = {
                    "url": auth.dev() ? oa_test_url : oa_online_url,
                    "type": "post-raw",
                    "data": data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, null);
                    }
                }
                EpgWeb.Dao.sendProxy(options)
            },
            //更新 epg 关联 oa info数据
            updateOaInfo:function( data,  handler){
                var options = {
                    url: "/api/program/oainfo",
                    dataType: 'json',
                    data: {data:JSON.stringify(data)},
                    method: 'post',
                    success: function (data) {
                        handler.call(this, data);
                    },
                    error: function (data) {
                        handler.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/oainfo');
            },

            // 节目添加
            setProgramAddData: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programAdd,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/add');
            },
            // 节目修改
            setProgramModifyData: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programEdit,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/program/edit');
            },
            // 节目删除
            deleteProgramData: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programDel,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };

                Ancestor.Dao.ajax(options, '/program/delete');
            },
            // 紧急检查
            forceCheckProgram: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programForceCheck,
                    dataType: 'json',
                    data: data,
                    method: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/forceCheck');
            },
            // 获取节目数据列表
            getProgramListByDay: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programList,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/program/list');
            },

            //检查 导播台
            createDirector:function(data, callback){
                var options = {
                    url: "http://dbt.lego.iqiyi.com/api/director/create",
                    dataType: 'json',
                    data: data,
                    type: 'post',
                    timeout: 10000,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                var authBase = Ancestor.Util.getAuth("/director/create");
                var header = {
                    Sign: "#f93Uc31K24()_@",
                    Time: authBase.clientTime,
                    From: authBase.from,
                    UserName: (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u')

                };
                // EpgWeb.Dao.sendProxy(options, {Sign: "#f93Uc31K24()_@"});
                EpgWeb.Dao.sendProxy(options, header);
            },

            //同步tvmao 节目 start
            syncTVmaoPrograms: function (data, callback) {
                var options = {
                    url: EpgWeb.urlConfig.programSyncUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, "/program/syncTVMao");
            },
            //同步tvmao 节目 end

            liveChannelType: function () {
                return this.getDataByName(this.cfgName.liveChannelType)
            },

            liveProgramType: function () {
                return this.getDataByName(this.cfgName.liveProgramType);
            },

            liveType: function () {
                return this.getDataByName(this.cfgName.LiveType);
            },

            episodeGradeType: function () {
                return this.getDataByName(this.cfgName.episodeGradeType);
            },
            logType: function () {
                return this.getDataByName(this.cfgName.LogType);
            },
            recommendRateType:function(){
                return this.getDataByName(this.cfgName.recommendRateType);
            },
            getChannel: function () {
                return this.getDataByName(this.cfgName.getChannel).data;
            },
            targetName: function () {
                return  this.getDataByName(this.cfgName.targetName);
            },
            getProgram: function () {
                var responseData = this.targetName();
                if (responseData == null || responseData.data == null || responseData.data.totalCount == 0) {
                    return null;
                }
                return responseData.data.result[0];
            }
        })

        Program.Dao.cfgName = $.extend({}, EpgWeb.Dao.cfgName,{
            from: "library",
            targetName: "entity",
            puyuData: "puyuData",
            live_temp_other:"live_temp_other",
            category_use:"category_use",
            fatherId: 0,
            id: 0,
            editPic: true,
            categoryArr: null
        });
    }
);
define('../program/Program.Util',['require','exports','module'],function (require, exports, module) {
    Program.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            qipuId: function (cellvalue, options, rowObject) {
                var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(rowObject.qipuId);
                return "<a target='_blank' href='" + plusUrl + "'>" + rowObject.qipuId + "</a>";
            },
            pname: function (cellvalue, options, rowObject) {
                if (rowObject.pageUrl != null) {
                    return "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>";
                }
                return cellvalue;
            },
            playStatus: function (cellvalue, options, rowObject) {
                if (cellvalue == null) {
                    return "Not exist ";
                }
                switch (cellvalue) {
                    case -1:
                        return "未设定";
                    case 0:
                        return "未开始";
                    case 1:
                        return "直播中";
                    case 2:
                        return "回看中";
                    case 3:
                        return "回看结束";
                    default :
                        return "Not exist value:" + cellvalue;
                }
                return cellvalue;
            },
            bossStatus: function (cellvalue, options, rowObject) {
                var enumValue = "";
                switch (cellvalue) {
                    case "FREE":
                        enumValue = "免费";
                        break;
                    case "PAIED_NOT_AVAILABLE":
                        enumValue = "<span style='color: red'>付费未划价</span>";
                        break;
                    case "PAIED_AVAILABLE":
                        enumValue = "<span style='color: red'>付费已划价</span>";
                        break;
                    default:
                        break;
                }
                return enumValue;
            },
            type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Program.Dao.liveProgramType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                return ret
            },
            episodeGrade: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Program.Dao.episodeGradeType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                if (ret == "A类一级") {
                    ret = "<span style='color: red'>" + ret + "</span>";
                }
                return ret;
            },
            log_type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Program.Dao.logType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                return ret;
            },

            channelName: function (cellvalue, options, rowObject) {
                var url = "http://epg.lego.iqiyi.com/epg/channel.html?channelName=" + encodeURIComponent(cellvalue.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">"));
                return "<a target='_blank' href='" + url + "'>" + cellvalue + "</a>";
            },
            onlineStatus: function (cellvalue, options, rowObject) {
                if (cellvalue == 0) {
                    return "删除";
                } else if (cellvalue == 1) {
                    return "启用";
                }
            },
            formal: function (cellvalue, options, rowObject) {
                if (cellvalue == 0) {
                    return "测试";
                } else if (cellvalue == 1) {
                    return "正式";
                }
            },
            oaDocEditorStatus: function (cellvalue, options, rowObject) {
                var ret = "";
                switch (cellvalue) {
                    case "unchecked":
                        ret = "待审核";
                        break;
                    case "checked":
                        ret = "总编室已确认";
                        break;
                    case "interrupt":
                        ret = "<span style='color: red'>中断</span>";
                        break;
                    default :
                        ret = "-"
                        break;
                }
                if (ret != "-") {
                    ret = "<a target='_blank' href='" + rowObject.oaDocUrl + "'>" + ret + "</a>"
                }
                return ret;
            },
            operate: function (cellvalue, options, rowObject) {
                var forceCheckStr = "";
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='Program.Util.jumpLibraryToEdit(" + rowObject.id + "," + rowObject.fatherId + ")'>编目</a>");
                if (Program.Config.AUTH_FORCE_CHECK && rowObject.channelLiveType == 2) {
                    htmlArr.push("<a href='javascript:;' onclick='Program.Util.checkProgram(" + rowObject.id + ")'>紧急检查</a>");
                }
                htmlArr.push(Program.Util.getBroadcastControl(rowObject));
                if (Program.Config.AUTH_FEED_VIEW && rowObject.channelLiveType == 2) {
                    htmlArr.push("<a href='javascript:;' onclick='Program.Util.checkFeed(" + rowObject.qipuId + ")'>查看feed</a>");
                }
                htmlArr.push("</br><a href='javascript:;' onclick='Program.Util.delProgram(" + rowObject.id + ")'>删除</a>");

                htmlArr.push("<a href='javascript:;' onclick='Program.Util.openHistory(" + rowObject.id + ")'>详细</a>");
                if (rowObject.directorEnable === 1) {
                    htmlArr.push("<a href='javascript:;' onclick='Program.Util.openDirector(" + rowObject.id + ")'>导播</a>")
                }
                if (rowObject.oaDocNo != null && rowObject.oaDocNo.length > 0 && Program.Config.oaTest) {
                    htmlArr.push("<br><a href='javascript:;' onclick='Program.Util.readOaStatus(\"" + rowObject.oaDocNo + "\")'>刷新oa单状态</a>")
                }
                return htmlArr.join("  ")
            },
            operate2: function (cellvalue, options, rowObject) {
                return "<a href='javascript:;' onclick='Program.Util.jumpListToEdit(" + rowObject.id + "," + rowObject.fatherId + ")'>编目</a>  " +
                    Program.Util.getBroadcastControl(rowObject) +
                    "<a href='javascript:;' onclick='Program.Util.delProgram(" + rowObject.id + ")'>删除</a>  " +
                    "<a href='javascript:;' onclick='Program.Util.openHistory(" + rowObject.id + ")'>详细</a>  ";
            },
            /**/
            publishStatus: function (checkValue) {
                if (checkValue == null)
                    return "";
                switch (checkValue) {
                    case 0:
                        return "未发布";
                    case 1:
                        return "已发布";
                    case 2:
                        return "页面下线";
                    case 3:
                        return "页面备用"
                    default:
                        return checkValue + "";
                }
            },
            purchase: function (checkValue) {
                if (checkValue == null)
                    return "";
                switch (checkValue) {
                    case 0:
                    case -100:
                        return "免费";
                    case 1:
                        return "收费";
                    default:
                        return checkValue + ""
                }

            },
            copyrightEndTime: function (checkValue) {
                if (checkValue == null) {
                    return "";
                }
                if (typeof( checkValue ) == "string") {
                    return checkValue;
                }
                if (checkValue <= 0) {
                    return "---";
                } else {
                    var date = new Date();
                    date.setTime(parseInt(checkValue));
                    return  EpgWeb.Util.formatDateTimeFormat(date);
                }
            },
            recommendRate: function (cellvalue, options, rowObject) {
                return Program.Config.RECOMMEND_RATE[cellvalue];
            },
            hot: function (cellvalue, options, rowObject) {
                if (rowObject.channelLiveType != 2) {
                    return "";
                }

                switch (cellvalue) {
                    case 0:
                        return "否";
                    case 1:
                        return "是";
                    default:
                        return "";
                }
            },
            test: function (cellvalue, options, rowObject) {
                if (rowObject.channelLiveType != 2) {
                    return "";
                }
                switch (cellvalue) {
                    case 0:
                        return "否";
                    case 1:
                        return "是";
                    default:
                        return "";
                }
            },
            publish_time: function (cellvalue, options, rowObject) {
                if (cellvalue != "") {
                    return EpgWeb.Util.formatDateTimeFormat(new Date(parseInt(cellvalue) * 1000));
                }
                return "";
            }
        },
        template: {
            daojuSuggest: function (itemArr) {
                return  '<div class="contract-item" >' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[0] + '</span>' +
                    '<span class="contract-width200" style="word-break:break-all">' + itemArr[1] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[2] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[3] + '</span>' +
                    '</div>'
            },
            voteSuggest: function (itemArr) {

                return '<div class="contract-item" >' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[0] + '</span>' +
                    '<span class="contract-width200" style="word-break:break-all">' + itemArr[1] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[2] + '</span>' +
                    '</div>';
            },
            albumSuggest: function (itemArr) {
                return   '<div class="contract-item" >' +
                    '<span class="contract-width100" style="word-break:break-all">' + itemArr[0] + '</span>' +
                    '<span class="contract-width150" style="word-break:break-all">' + itemArr[1] + '</span>' +
                    '<span class="contract-width60" style="word-break:break-all">' + itemArr[2] + '</span>' +
                    '<span class="contract-width120" style="word-break:break-all">' + itemArr[3] + '</span>' +
                    '<span class="contract-width80" style="word-break:break-all">' + itemArr[4] + '</span>' +
                    '<span class="contract-width80" style="word-break:break-all">' + itemArr[5] + '</span></div>'
            },
            puyuSuggest: function (itemArr) {
                var formatArr = [];
                formatArr.push('<span class="contract-width200" style="word-break:break-all">' + itemArr[0] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[1] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[2] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[3] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[4] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[5] + '</span>');
                formatArr.push('<span class="contract-width120" style="word-break:break-all">' + itemArr[6] + '</span>');
                formatArr.push('<span class="contract-width100" style="word-break:break-all">' + itemArr[7] + '</span>');
                formatArr.push('<span class="contract-width200" style="word-break:break-all">' + itemArr[8] + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },
            qitanSuggest: function (itemArr) {
                var formatArr = [];
                formatArr.push('<span class="contract-width80" style="word-break:break-all">' + itemArr[0] + '</span>');
                formatArr.push('<span class="contract-width250" style="word-break:break-all">' + itemArr[1] + '</span>');
                formatArr.push('<span class="contract-width80" style="word-break:break-all">' + itemArr[2] + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },
            actorSuggest: function (itemArr) {
                var formatArr = [];
                formatArr.push('<span class="contract-width100" style="word-break:break-all">' + itemArr[0] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[1] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[2] + '</span>');
                formatArr.push('<span class="contract-width50" style="word-break:break-all">' + itemArr[3] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[4] + '</span>');
                formatArr.push('<span class="contract-width150" style="word-break:break-all">' + itemArr[5] + '</span>');
                return '<div class="contract-item" >' + formatArr.join("") + '</div>';
            },
            playbackSuggest: function (itemArr) {
                return this.albumSuggest(itemArr);
            },
            templateSuggest: function (item) {
                return this.albumSuggest([
                    item["id"],
                    item["label"] ,
                    item["channelName"] ,
                    this.formatter.copyrightEndTime(item.copyrightEndTime),
                    this.formatter.purchase(item.isPurchase),
                    this.formatter.publishStatus(item.pagePublishStatus)
                ])
            }
        },
        setContainer: function ($container) {
            this.$container = $container;
        },
        // 绑定节目编辑事件
        bindEditEvent: function ($container) {

            this._editBindEvent($container);
            this._initEditData($container);

            this._liveTypeLinkage();
            this._initEditEvent();
        },

        _initEditEvent: function () {
            var self = this;
        },
        dispatchLiveChannelType: function (objKey, objValue) {
            return (  parseInt(objKey) < 5 && objValue == "1") ||
                (parseInt(objKey) > 5 && objValue == "2" ) ||
                (  parseInt(objKey) == 5 && objValue == "3" )
        },
        getBroadcastControl: function (rowObj) {
            var hasStream = null != rowObj.channelHasStream && rowObj.channelHasStream == 1;
            if (hasStream) {
                return "<a href='javascript:;' onclick='Program.Util.jumpToBroadcast(" + rowObj.id + "," + rowObj.fatherId + ")'>播控中心</a> ";
            } else {
                return "<a class='disabled'>播控中心</a> ";
            }
        },
        jumpLibraryToEdit: function (entityId, fatherId) {
            var openUrl = "program_edit.html?id=" + entityId + "&from=library&fatherId=" + fatherId;
            window.open(openUrl);
        },
        jumpListToEdit: function (entityId, fatherId) {
            var openUrl = "program_edit.html?id=" + entityId + "&from=list&fatherId=" + fatherId;
            window.open(openUrl);
        },
        jumpListToAdd: function (fatherId) {
            var openUrl = "program_edit.html?from=list&fatherId=" + fatherId;
            window.open(openUrl);
        },
        jumpToBroadcast: function (entityId, fatherId) {
            var openUrl = "broadcast_manager_episode.html?programId=" + entityId + "&id=" + fatherId;
            window.open(openUrl);
        },
        jumpToDirector: function (programQipuId) {
            var openUrl = (auth.dev() ? "" : "http://dbt.lego.iqiyi.com/epg/") + "program_director.html?programQipuId=" + programQipuId
            window.open(openUrl);
        },

        checkProgram: function (entityId) {
            Program.Dao.doAuthData({
                url: '/epg/auth/forceCheck',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: '很抱歉，您没有权限!', type: "error"})
                },
                doSuccess: function () {
                    Program.Dao.forceCheckProgram({id: entityId }, function (data) {
                        if (data.code == "A00000") {
                            EpgWeb.Plugin.showTips({ content: data.msg})
                        } else {
                            EpgWeb.Plugin.showTips({ content: data.msg, type: "error"})
                        }
                    })
                }
            })
        },
        checkFeed: function (entityQipuId) {
            var options = {
                url: EpgWeb.urlConfig.getQiPuBaseUrl(entityQipuId),
                type: "get",
                success: function (data) {
                    if (data != null) {
                        var array = [];
                        if(data.feed_summary != null){
                            $.each(data.feed_summary, function (i, elemt) {
                                array.push(elemt.entity_id);
                            })
                        }
                        Program.Util.doQueryFeed(array.join(","));
                    } else {
                        EpgWeb.Plugin.showTips({ content: "获取feed数据失败", type: "error"})
                    }
                },
                error: function (error) {
                    console.log("no data");
                }
            }
            EpgWeb.Dao.sendProxy(options);
        },
        doQueryFeed: function (feedIds) {
            $('#feedList').clearGridData();
            var options = {
                url: Program.Constant.query_feed_url,
                data: {feed_ids: feedIds, filterDelFeed: 0,agentversion:"9.3.0"},
                type: "get",
                success: function (data) {
                    if (data != null) {
                        Program.Config.PageBeanFeed.setNewData(data.data.list, 10)
                        $("#feedDiv").dialog("open");
                        $('#feedList')[0].addJSONData(Program.Config.PageBeanFeed.getCur())
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            }
            $.ajax(options);
        },
        checkPlaying: function () {
            var self = this;
            var aimGrid = $("#list");
            var dataOriginl = aimGrid.jqGrid("getData");
            var current = self.formatDateTimeFormat(new Date());
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            $.each(dataOriginl, function (i, element) {
                if (element.startPlayTime <= current && current <= element.endPlayTime) {
                    console.log(" id:" + element.id);
                    aimGrid.setCell(element.id, "startPlayTime", '', {backgroundColor: "#3cb371"}, true);
                    aimGrid.setCell(element.id, "endPlayTime", '', {backgroundColor: "#3cb371"}, true)
                }
            });
        },
        delProgram: function (entityId, fatherId) {
            Program.Dao.doAuthData({
                url: '/epg/program_delete.html',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: '很抱歉，您没有删除的权限!', type: "error"})
                },
                doSuccess: function () {
                    SystemDialog.queryConfirm("确认删除？", function (flag) {
                        if (flag === true) {
                            Program.Dao.deleteProgramData({id: entityId }, function (data) {
                                Program.Util.reloadHandler(data);
                            })
                        }
                    })
                }
            })
        },
        openDirector: function (entityId) {
            var dataArr = $("#list").getData();
            var selectEntity = null;
            $.each(dataArr, function (i, element) {
                if (element.id == entityId) {
                    selectEntity = element;
                    return false;
                }
            })
            if (selectEntity == null || selectEntity.directorEnable != 1) {
                return;
            }
            var forbidTime = new Date(selectEntity.endPlayTime.replace(/-/g, "/"))
            forbidTime.setDate(forbidTime.getDate() + 3);
            if (Date.now() > forbidTime.getTime()) {
                SystemDialog.queryAlert("导播台已经被回收!")
                return;
            }
            var newData = {
                programQipuId: selectEntity.qipuId,
                programName: selectEntity.pname,
                startPlayTime: selectEntity.startPlayTime,
                stopPlayTime: selectEntity.endPlayTime,
                source: 1,
                delay: 10,
                outputStreamType: "RESOLUTION_720P"
            };

            Program.Dao.doAuthData({
                url: '/epg/program_director.html',
                doError: function () {
                    EpgWeb.Plugin.showTips({content: '很抱歉，您没有导播的权限!', type: "error"})
                },
                doSuccess: function () {
                    Program.Dao.createDirector({"entity": JSON.stringify(newData)}, function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({content: 'director/create 请求异常', type: "error"})
                        } else if (data.code != "A00000") {
                            if (data.data == "-1003") {
                                EpgWeb.Plugin.showTips({content: "第三方接口调用失败", type: "error"})

                            } else if (data.data == "-1005") {
                                EpgWeb.Plugin.showTips({content: "导播资源已回收", type: "error"})
                            } else {
                                EpgWeb.Plugin.showTips({content: data.msg, type: "error"})
                            }
                        } else {
                            Program.Util.jumpToDirector(newData.programQipuId);
                        }
                    });
                }
            })
        },
        readOaStatus: function (oaDocNo) {
            Program.Dao.readOaStatus(
                {"queryParam": oaDocNo,
                    "domainUser": auth.baseInfo.authInfo.email.replace("@qiyi.com", "")},
                function (data) {
                    if (data != null && data.code == "2000") {
                        if (data.message.length == 1) {
                            var newData = data.message[0];
                            var updateEntity = {};
                            updateEntity.docNo = newData.docNo;
                            updateEntity.docStatus = newData.docStatus;
                            updateEntity.liveLevel = newData.liveLevel;
                            updateEntity.liveLevelABC = newData.liveLevelABC;
                            updateEntity.chiefEditorApprovalStatus = newData.chiefEditorApprovalStatus
                            Program.Dao.updateOaInfo(updateEntity, function (rdata) {
                                if (rdata != null) {
                                    EpgWeb.Plugin.showTips({content: rdata.msg, type: rdata.code == "A00000" ? "success" : "error"});
                                    if (rdata.code == "A00000") {
                                        $("button.query-btn").click()
                                    }
                                } else {
                                    console.log("请求失败");
                                }
                            })
                        }
                    } else {
                        console.log("readOaStatus");
                    }
                })
        },

        openHistory: function (entityId) {
            Program.Dao.doAuthData({
                url: '/epg/channel_log.html',
                doSuccess: function () {
                    Program.Config.AUTH_LOG_DETAIL = true;
                },
                doFinal: function () {
                    var tableConfig = $.extend(true, {}, Program.Config.TABLE_LOG);
                    tableConfig.width = Program.Config.AUTH_LOG_DETAIL ? 875 : 425
                    var colModel = tableConfig.colModel;
                    var newColModel = [];
                    var colModelConfig = Program.Config.TABLE_COLMODEL_CONFIG;

                    $.each(colModel, function (i, model) {
                        newColModel.push(colModelConfig[model]);
                    });
                    tableConfig.colModel = newColModel;
                    tableConfig.colModel[4].hidden = !Program.Config.AUTH_LOG_DETAIL;
                    $('#logList').jqGrid(tableConfig);
                    $("#programLogDiv").dialog({
                        title: "历史记录",
                        autoOpen: false,
                        width: Program.Config.AUTH_LOG_DETAIL ? 900 : 450,
                        height: 600,
                        modal: true,
                        dialogClass: 'alert',
                        open: function () {
                            $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                        }
                    });
                    $("#programLogDiv").dialog("open");
                    $('#logList').jqGrid('setGridParam', {
                        page: 1,
                        datatype: "json",
                        postData: {id: entityId}
                    }).trigger('reloadGrid');
                }
            })
        },
        getValidator: function ($container, config) {
            // var $container = this.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, config);

            return validator;
        },
        //daoju  relation start

        createSign: function (obj, daoju_secret) {
            var self = this;
            var str = '';
            $.each(obj, function (k) {
                str += k + obj[k];
            });
            str += daoju_secret;
            console.log(str);
            return self.hex_sha1(self.utf16to8(str));
        },
        utf16to8: function (str) {
            var out, i, len, c;
            out = "";
            len = str.length;
            for (i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                } else if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                } else {
                    out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                }
            }
            return out;
        },

        hex_sha1: function (str) {
            var hexcase = 0;
            var chrsz = 8;

            function dosha1(s) {
                return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
            }

            function binb2hex(binarray) {
                var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
                var str = "";
                for (var i = 0; i < binarray.length * 4; i++) {
                    str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
                }
                return str;
            }

            function core_sha1(x, len) {
                x[len >> 5] |= 0x80 << (24 - len % 32);
                x[((len + 64 >> 9) << 4) + 15] = len;

                var w = Array(80);
                var a = 1732584193;
                var b = -271733879;
                var c = -1732584194;
                var d = 271733878;
                var e = -1009589776;

                for (var i = 0; i < x.length; i += 16) {
                    var olda = a;
                    var oldb = b;
                    var oldc = c;
                    var oldd = d;
                    var olde = e;

                    for (var j = 0; j < 80; j++) {
                        if (j < 16) w[j] = x[i + j];
                        else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                        var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
                        e = d;
                        d = c;
                        c = rol(b, 30);
                        b = a;
                        a = t;
                    }

                    a = safe_add(a, olda);
                    b = safe_add(b, oldb);
                    c = safe_add(c, oldc);
                    d = safe_add(d, oldd);
                    e = safe_add(e, olde);
                }
                return Array(a, b, c, d, e);

            }

            function sha1_ft(t, b, c, d) {
                if (t < 20) return (b & c) | ((~b) & d);
                if (t < 40) return b ^ c ^ d;
                if (t < 60) return (b & c) | (b & d) | (c & d);
                return b ^ c ^ d;
            }

            function sha1_kt(t) {
                return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
            }

            function safe_add(x, y) {
                var lsw = (x & 0xFFFF) + (y & 0xFFFF);
                var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
                return (msw << 16) | (lsw & 0xFFFF);
            }

            function rol(num, cnt) {
                return (num << cnt) | (num >>> (32 - cnt));
            }

            function str2binb(str) {
                var bin = Array();
                var mask = (1 << chrsz) - 1;
                for (var i = 0; i < str.length * chrsz; i += chrsz)
                    bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
                return bin;
            }

            return dosha1(str);
        },
        reloadHandler: function (data) {
            if (data != null) {
                EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                if (data.code == "A00000") {
                    $("#list").trigger("reloadGrid")
                }
            } else {
                console.log("callbackHandler no return data");
            }
        },
        calculateDate: function (str) {//month 7days yestoday today
            var from_date = "", to_date = "";
            var d = new Date();
            var defaultEnd = this.formatDateTimeFormat(d);
            this.setZeroTime(d);
            switch (str) {
                case "today":
                    from_date = this.formatDateTimeFormat(d);
                    d.setDate(d.getDate() + 1);
                    to_date = this.formatDateTimeFormat(d);
                    break;
                case "yesterday":
                    d.setDate(d.getDate() - 1);
                    from_date = this.formatDateTimeFormat(d);
                    this.setDayLastTime(d);
                    to_date = this.formatDateTimeFormat(d);
                    break;
                case "2days":
                    from_date = this.formatDateTimeFormat(d);
                    d.setDate(d.getDate() + 2);
                    to_date = this.formatDateTimeFormat(d);
                    break;
                case "7days":
                    from_date = this.formatDateTimeFormat(d);
                    d.setDate(d.getDate() + 7);
                    to_date = this.formatDateTimeFormat(d);
                    break;
                case "7days+":
                    $("input[name=endDate]").datetimepicker("option", "minDate", "");
                    $("input[name=endDate]").datetimepicker("option", "minDateTime", null);
                    $("input[name=startDate]").datetimepicker("option", "maxDate", "");
                    $("input[name=startDate]").datetimepicker("option", "maxDateTime", null);
                    $("input[name=endDate]").val("")
                    d.setDate(d.getDate() + 7);
                    from_date = this.formatDateTimeFormat(d);
                    to_date = null;
                    break;
                case "absToday":
                    from_date = this.formatDateTimeFormat(d);
                    this.setDayLastTime(d);
                    to_date = this.formatDateTimeFormat(d);
                    break;
                case "absToday+":
                    this.setZeroTime(d);
                    d.setHours(10);
                    from_date = this.formatDateTimeFormat(d);
                    d.setDate(d.getDate() + 1);
                    to_date = this.formatDateTimeFormat(d);
                    break;
            }
            if (to_date != null) {
                this.bindDate("startDate", "endDate", { maxDate: to_date, maxDateTime: new Date(to_date.replace(/-/g, "/")), minDate: from_date, minDateTime: new Date(from_date.replace(/-/g, "/"))})
                $("input[name=startDate]").datetimepicker("setDate", new Date(from_date.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate", new Date(to_date.replace(/-/g, "/")));
            } else {
                this.bindDate("startDate", "endDate", { maxDate: "", maxDateTime: null, minDate: from_date, minDateTime: new Date(from_date.replace(/-/g, "/"))})
                $("input[name=startDate]").datetimepicker("setDate", new Date(from_date.replace(/-/g, "/")));
            }
        },

        RemoteCheck: (function () {
            var timerId = -1;
            var _handler = null;
            var _startHandler = null;
            var _data = [];

            function startCheck() {
                _startHandler.call(this, _data);
                return setInterval(checkComplete, 16);
            }

            function checkComplete() {
                var allComplete = true;
                $.each(_data, function (index, element) {
                    if (!element.complete) {
                        allComplete = false
                        return true;
                    }
                })
                if (allComplete) {
                    clearInterval(timerId);
                    timerId = -1;
                    console.log("check data over");
                    _handler(_data);
                }
            }

            function doCheck(data, handler, startHandler) {
                if (timerId > 0) {
                    console.log("wait to remote check")
                    return;
                }
                _handler = handler;
                _startHandler = startHandler;
                if (data != null) {
                    if ($.isArray(data)) {
                        _data = data;
                    } else {
                        _data = [data];
                    }
                }
                if (_data == null || _data.length == 0) {
                    handler.call(null)
                    return;
                }

                if (timerId < 0) {
                    timerId = startCheck();
                }
            }

            function clear() {
                _data = [];
            }

            function addToCheck(checkData) {
                _data.push(checkData)
            }

            return{
                clear: clear,
                doCheck: doCheck,
                addToCheck: addToCheck
            }
        })()
    });


});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../program/Program.Task',['require','exports','module'],function (require, exports, module) {
        Program.Task = $.extend({}, EpgWeb.Task, {
            getLiveProgramType: function (taskName , handler) {
                var self = this;
                if(handler == null ){
                    handler =  function (data) {
                        var selectJDom = $("select[name=liveProgramType]");
                        $("<option value=''>请选择</option>").appendTo(selectJDom);
                        if (data.data != null) {
                            $.each(data.data, function (index, obj) {
                                $("<option>", {
                                    value: obj.key,
                                    html: obj.descr
                                }).appendTo(selectJDom);
                            });
                        }
                        selectJDom.bind("change", function (event) {
                            if (event.currentTarget.value == 1) {
                                $("#sportContainer").show()
                            } else {
                                $("#sportContainer").hide()
                            }
                        })
                    }
                }
                return self.getConfigType(taskName,handler);
            },
            getLegoChannelType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("#channelCateTag");
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.val
                        }).appendTo(selectJDom);
                    });
                })
            },
            getTargetName: function (regName, data) {
                return {
                    regName: regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.programList,
                        dataType: "json",
                        data: data
                    }
                }
            },

            getLiveTmpOtherType: function (regName, data) {
                var self = this;
                return self.getConfigType(regName, function (data) {
                    var selectJDom = $("#" + regName);
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.val,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                })
            },

            getLiveChannelType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            },

            getLogType:function(taskName){
                var self = this;
                return self.getConfigType(taskName)
            },
            getLiveType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("select[name=liveType]");
                    var selectChild = $("select[name=liveChannelType]");
                    selectChild.hide();
                    if (data.data == null) {
                        return
                    }
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                    selectJDom.bind("change", function (event) {
                        selectChild.show();
                        selectChild.html("");
                        var appendChildren = [];
                        $.each(Program.Dao.liveChannelType().data, function (index, obj) {
                            if (Program.Util.dispatchLiveChannelType(obj.key, event.currentTarget.value)) {
                                appendChildren.push($("<option>", {
                                    value: obj.key,
                                    html: obj.val
                                }));
                            }
                        });
                        if (appendChildren.length == 0) {
                            selectChild.hide();
                        } else {
                            appendChildren = [$("<option value=''>请选择</option>")].concat(appendChildren)
                        }
                        $.each(appendChildren, function (i, element) {
                            element.appendTo(selectChild);
                        })
                    })
                })
            },
            sendTask: function (modelData, sendImageDatas) {
                return {
                    regName: null,
                    options: {
                        type: "post",
                        dataType: "json",
                        data: {"data": JSON.stringify(modelData), "imageDatas": sendImageDatas == null ? null : JSON.stringify(sendImageDatas) },
                        success: function (data) {
                            //   callback
                        },
                        error: function (data) {

                        }
                    }
                }
            },

            getGradeType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("select[name=episodeGrade]");
                    $("<option>", {value: "", html: "请选择"}).appendTo(selectJDom);
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                })
            },
            getRecommendType: function (taskName) {
                var self = this;
                return self.getConfigType(taskName, function (data) {
                    var selectJDom = $("select[name=recommend_rate]");
                    $("<option>", {value: "", html: "请选择"}).appendTo(selectJDom);
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                })
            }


        })
    }
);
define(
    '../program/Program.Grid',['require','exports','module'],function (require, exports, module) {
        Program.Grid = function (options) {
            this.dao = Program.Dao;
            this.task = Program.Task;
            this.config = Program.Config;
            this.options = options || {};
        };
        Com.inherits(Program.Grid, Ancestor.Grid).extend({
            /* program library start*/
            runLibrary: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.$feedGrid = self.options.$feedGrid;
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramType(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getLiveChannelType(self.dao.cfgName.liveChannelType));
                taskArr.push(self.task.getLiveType(self.dao.cfgName.LiveType));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
                taskArr.push(self.task.getGradeType(self.dao.cfgName.episodeGradeType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                self.config.oaTest = Com.url.getParameter("oatest")==="1";
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startLibrary();
                })
                self.config.PageBeanFeed = Program.Util.createPageBean();
                self.initRecommendRate();
                self.initLibraryAuth();
            },
            initLibraryAuth:function(){
                var self = this;
                self.readyCount = 0;
                self.finalCount = 2;
                self.initOver = false;
                auth.getAuthData({tips: 1, url: '/epg/auth/forceCheck'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_FORCE_CHECK = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/feedView'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_FEED_VIEW = true;
                    }
                    self.phaseOver();
                })
            },
            phaseOver: function () {
                var self = this;
                self.readyCount++;
                if (!self.initOver && self.readyCount == self.finalCount) {
                    self.initOver = true;
                    EpgWeb.ajaxQueue.startLoad();
                }
            },
            startLibrary: function (options, callback) {
                var self = this;
                self.bindBasicEvent();
                self.initFeedDialog();
                console.log("load complete startLibrary");
                EpgWeb.Util.bindDate("startDate", "endDate");
                var currentDate = new Date()
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() - 2 * 86400000);
                $("input[name=startDate]").datetimepicker("setDate", currentDate);
                self.initLibraryGrid.call(self, {}, callback);
                self.initFeedGrid.call(self, {}, callback);
            },

            initLibraryGrid: function (options, callback) {
                var self = this;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_LIBRARY);
                //params.rowNum=10;
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
                self.echoQuery();
            },

            initFeedGrid:function(options, callback){
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_FEED);
                self.$feedGrid.jqGrid(gridConfig);
            },

            echoQuery: function () {
                var self = this;
                self.query();
            },

            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },

            reload: function () {
                var self = this;
                var $grid = self.$grid;
                $grid.trigger('reloadGrid');
            },

            getParam: function () {
                var self = this;
                var $container = self.options.$container;

                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name;
                var key;
                $.each($elements, function () {
                    name = this.name;
                    if (name) {
                        if (this.type == 'radio') {
                            params[name] = $('input[name="' + name + '"]:checked').val() || '';
                        } else
                            params[name] = $.trim($(this).val()) || '';
                    }
                });
                var formal = Com.url.getParameter("formal");
                if (formal) {
                    params.formal = formal;
                }
                params.fromPath = "library";
                var today = Com.url.getParameter("today");
                if (today) {
                    $('#absToday').show();
                    $('#absToday+').show();
                }
                return params;
            },

            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                $form.find('.query-btn').on('click', function () {
                    self.query();
                    return false;
                });
                $form.find('button[type="reset"]').click(function () {
                    $("select[name=liveChannelType]").hide();
                    self.resetQueryForm();
                    self.updateFormLayoutWithLiveType(0);
                });

                $form.find('select[name=liveType]').bind("change", function (event) {
                    var $curTarget = $(event.currentTarget);
                    var selectedValue = $curTarget.val();
                    self.updateFormLayoutWithLiveType(selectedValue);
                });
                self.updateFormLayoutWithLiveType(0);

                //$form.find("select[name=playStatus]").val(1);

            },
            initDialog: function () {
                var self = this;
                $("#modifyDiv").dialog({
                    title: "打点项目明细",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $("#modifyDiv").find("form").trigger("reset");
                        $("#modifyDiv").find("input[name=channel_code]").removeAttr("readonly");
                        $("#modifyDiv").find("input[name=channel_addr]").removeAttr("readonly");
                        $("#modifyDiv").find("select[name=server_region2]").change();
                    }
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            initFeedDialog:function(){
                $("#feedDiv").dialog({
                    title: "查看已发布feed",
                    autoOpen: false,
                    width: 820,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },

            /* program library end */
            /* program list start  */
            runDayList: function (options, callback) {
                var self = this;
                self.$grid = $('#list');
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramType(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getLiveChannelType(self.dao.cfgName.liveChannelType));
                taskArr.push(self.task.getLiveType(self.dao.cfgName.LiveType));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
                taskArr.push(self.task.getGradeType(self.dao.cfgName.episodeGradeType));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: fatherId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startDayList();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            startDayList: function (options, callback) {
                var self = this;
                $("button[name=newProgram]").hide();
                $("button[name=tvmaoCall]").hide();
                var element = self.dao.getChannel()
                if (element != null) {
                    switch (element.liveType) {
                        case 1:
                            //  $("button[name=tvmaoCall]").show();
                            break;
                        case 2:
                            $("button[name=newProgram]").show();
                            break;
                    }
                }
                self.initDayList({});
                self.bindListBasicEvent()
                self.initWeekToolBar();
            },
            initDayList: function (options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                self.$grid.jqGrid(gridConfig);
                self.bindDayTListEvent();
                //self.echoQuery();
            },

            listQuery: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getListParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getListParam: function () {
                var self = this;
                return  {
                    startDate: Program.Config.dateTime + " 00:00:00",
                    endDate: Program.Config.dateTime + " 23:59:59",
                    fatherId: self.dao.channelId,
                    fromPath: "library",
                    pageSize: 40}
            },

            initWeekToolBar: function () {
                var self = this;
                Program.Util.WeekManager = EpgWeb.Util.createWeekManager($("#dayRange div label"));
                var weekRangeLabel = $("#weekRange label");
                $(weekRangeLabel[0]).bind("click", function () {
                    Program.Util.WeekManager.preWeek();
                });
                $(weekRangeLabel[1]).bind("click", function () {
                    self.updateTableByDate(Program.Util.WeekManager.quickToCurrentWeek());
                })
                $(weekRangeLabel[2]).bind("click", function () {
                    Program.Util.WeekManager.nextWeek()
                })
                $("button.left").bind("click", function () {
                    Program.Util.WeekManager.preWeek()
                })

                $("button.right").bind("click", function () {
                    Program.Util.WeekManager.nextWeek()
                })

                $("#dayRange div label").bind("click", function (event) {
                    var aChild = event.currentTarget;
                    $(aChild).parent().find("label").removeClass("selected");
                    $(aChild).addClass("selected");
                    self.updateTableByDate(aChild.getAttribute("query-date"))
                })
                self.updateTableByDate(Program.Util.WeekManager.quickToCurrentWeek());
            },

            updateTableByDate: function (lDateFormat) {
                var self = this;
                Program.Config.dateTime = lDateFormat;
                self.$grid.setGridParam({page: 1, url: EpgWeb.urlConfig.programList, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: self.getListParam()}).trigger("reloadGrid");
            },

            bindListBasicEvent: function () {
                var self = this;
                $("button[name=newProgram]").bind("click", function (event) {
                    Program.Util.jumpListToAdd(self.dao.channelId);
                })
                $("button[name=tvmaoCall]").removeAttr("disabled");
                $("button[name=tvmaoCall]").bind("click", function (event) {
                    $("button[name=tvmaoCall]").prop("disabled", true);
                    self.syncQuery(self.dao.channelId)
                })
            },

            bindDayTListEvent: function () {
                var self = this;
                $("<span style='color:#187ddb;font-weight:normal'>提示：直播视频只能回看二天！</span>").appendTo($("#t_list"));
                var bdiv = $(".ui-jqgrid-bdiv");
                $("<label style='width: 40px;float:right;'>PM</label>").bind("click", function () {
                    if (bdiv[0].scrollHeight <= bdiv[0].clientHeight) {
                        return;
                    }
                    var allDate = self.$grid.jqGrid("getRowData");
                    var checkPM = "";
                    var interrupt = 0;
                    for (var i = 0; i < allDate.length; i++) {
                        checkPM = allDate[i].startPlayTime.substr(11);
                        if (checkPM >= "12:00:00") {
                            interrupt = i;
                            break;
                        }
                    }
                    bdiv.scrollTop(interrupt / allDate.length * bdiv[0].scrollHeight)
                }).appendTo($("#t_list"));
                $("<label style='width: 40px;float:right;'>AM</label>").bind("click", function () {
                    bdiv.scrollTop(0)
                }).appendTo($("#t_list"))
            },

            /* program list end  */

            /* program grid operation  */
            syncQuery: function (fatherId) {
                var self = this;
                self.dao.syncTVmaoPrograms({fatherId: fatherId}, function (data) {
                    SystemDialog.queryAlert(data.msg);
                    if (data.code == "A00000") {
                        $("button[name=tvmaoCall]").removeAttr("disabled");
                        self.reload();
                    }
                })
            },

            initRecommendRate: function () {
                var self = this;
                var selectJDom = $("select[name=recommendRate]");
                $("<option>", {value: '', html: "全部", selected: true}).appendTo(selectJDom);
                $.each(Program.Config.RECOMMEND_RATE, function (index, obj) {
                    $("<option>", {
                        value: index,
                        html: obj
                    }).appendTo(selectJDom);
                });
            },

            updateFormLayoutWithLiveType: function (val) {
                if (val == 2) {
                    //$("#recommendRateDiv").show();
                    $("#hotDiv").show();
                    $("#testDiv").show();
                } else {
                    //$("#recommendRateDiv").hide();
                    $("#hotDiv").hide();
                    $("#testDiv").hide();
                }
            }
        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Zhibo.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../zhibo/Zhibo',['require','exports','module'],function(require, exports, module) {
        window.Zhibo = window.Zhibo || {
            version: '1.0'
        };
        Zhibo.Constant = {
            baseApiUrl:(auth.dev() ? "http://10.23.70.33:7000/":"http://dot.live.qiyi.domain/"),
            thirdUrl_liveList_monitor :"http://lego.iqiyi.com/live2VOD/liveList/monitor",
            thirdUrl_query_user:"http://lego.iqiyi.com/external/auth/auth-api/services/user/search",
            epgBaseApiUrl: "/api/",
            devMode: auth.dev()
        }

        Zhibo.urlConfig = (function () {
            var useUrl = Zhibo.Constant.baseApiUrl;
            var modify = useUrl+"v1/channel/modify";
            var channel = useUrl+"v1/channel";
            var machinelist= useUrl+"v1/channel/machinelist";
            var machinemodify = useUrl + "v1/channel/machinemodify";
            var ipServerTemp = "http://@ipServer:8080/";
            var dotLoad = ipServerTemp + "dot/load?from_client=true";
            var version = ipServerTemp + "version";
            var channelInfo = ipServerTemp + "channel/channelinfo";
            var submitLogUrl = Zhibo.Constant.epgBaseApiUrl+"vod/saveLog";
            var logListUrl = Zhibo.Constant.epgBaseApiUrl+"vod/logList";
            var logListFilterUrl = Zhibo.Constant.epgBaseApiUrl+"vod/logList/filter";
            var recordListUrl = Zhibo.Constant.epgBaseApiUrl+"vod/vodRecord/getList";
            var recordEditUrl = Zhibo.Constant.epgBaseApiUrl+"vod/vodRecord/edit";
            var recordAddUrl = Zhibo.Constant.epgBaseApiUrl+"vod/vodRecord/add";
            var recordDelUrl = Zhibo.Constant.epgBaseApiUrl+"vod/vodRecord/del";
            return {
                modifyUrl:modify,
                machinemodifyUrl:machinemodify,
                channelUrl:channel,
                machinelistUrl:machinelist,
                dotLoadUrl:dotLoad,
                versionUrl:version,
                channelInfoUrl:channelInfo,
                submitLogUrl:submitLogUrl,
                logListUrl:logListUrl,
                recordListUrl:recordListUrl,
                recordEditUrl:recordEditUrl,
                recordAddUrl:recordAddUrl,
                recordDelUrl:recordDelUrl,
                logListFilterUrl:logListFilterUrl
            }
        })()
    }
);
define(
    '../zhibo/Zhibo.Action',['require','exports','module'],function (require, exports, module) {
        Zhibo.Action = (function () {
            var listGrid = null;
            // 表格

            var getListGrid = function (options) {
                if (!listGrid) {
                    listGrid = new Zhibo.Grid($.extend(true, {
                        // '$container': $('#ChannelListContainer'),
                        type: 0
                    }, options));
                }
                return listGrid;
            }

            function writePointRun(){
           //     Ancestor.Config.EPG_AUTH.list = '/program/list';
                listGridRun({});
            }

            function listGridRun(options){
                listGrid = getListGrid(options);
                listGrid.runList();
                console.log('list grid run');
            }

            return {
                writePointRun:writePointRun
            }
        })();
    }
);
///import js-src/lib/
///import js-src/com/
define('../zhibo/Zhibo.Config',['require','exports','module'],function (require, exports, module) {
    Zhibo.Config = $.extend({}, Ancestor.Config, {
        TABLE_COLMODEL_CONFIG: {
            channel_id: {
                name: "channel_id",
                index: 'channel_id',
                width: 120,
                title: false,
                sortable: false,
                hidden: true
            },
            channel_name: {
                name: "channel_name",
                index: 'channel_name',
                title: false,
                width: 120,
                sortable: false
            },
            channel_code: {
                name: "channel_code",
                index: 'channel_code',
                title: false,
                width: 120,
                sortable: false,
                align: "center"
            },
            channel_addr: {
                name: "channel_addr",
                index: 'channel_addr',
                title: false,
                width: 300,
                sortable: false
            },
            channel_ip: {
                name: "channel_ip",
                index: 'channel_ip',
                title: false,
                width: 100,
                sortable: false,
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.channel_ip(v, o, r);
                }
            },
            ip: {
                name: "ip",
                index: 'ip',
                title: false,
                width: 100,
                sortable: false
            },
            freeType: {
                name: "freeType",
                index: 'freeType',
                title: false,
                width: 50,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.freeType(v, o, r);
                }
            },
            channel_status: {
                name: "channel_status",
                index: 'channel_status',
                title: false,
                width: 80,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.channel_status(v, o, r);
                }
            },
            operate2: {
                //wait to do
                title: false,
                sortable: false,
                width: 835,
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.operate2(v, o, r);
                }
            },
            operate3: {
                title: false,
                sortable: false,
                width: 120,
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.operate3(v, o, r);
                }
            },
            region: {
                name: "region",
                index: 'region',
                title: false,
                width: 180,
                sortable: false,
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.region(v, o, r);
                }
            },
            location: {
                name: "location",
                index: 'location',
                title: false,
                width: 180,
                sortable: false,
                hidden: true
            },
            loc_id: {
                name: "loc_id",
                index: 'loc_id',
                title: false,
                width: 180,
                sortable: false,
                hidden: true
            },

            log_id: {
                name: 'id',
                index: 'id',
                title: false,
                sortable: false,
                hidden: true
            },
            log_addTime: {
                name: 'addTime',
                index: 'addTime',
                sortable: false,
                title: false,
                width: 150,
                align: 'center'
            },
            log_user: {
                name: 'user',
                index: 'user',
                sortable: false,
                title: false,
                width: 150
            },
            log_type: {
                name: 'type',
                index: 'type',
                sortable: false,
                title: false,
                width: 120,
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.log_type(v, o, r);
                }
            },
            log_descr: {
                name: "descr",
                index: 'descr',
                title: false,
                width: 450,
                sortable: false,
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.log_descr(v, o, r);
                }
            },
            record_creator:{
                name: 'opUser',
                index: 'opUser',
                sortable: false,
                title: false,
                width: 150
            },
            record_start_time:{
                name: 'startTime',
                index: 'startTime',
                sortable: false,
                title: false,
                width: 150,
                align: 'center'
            },
            record_end_time:{
                name: 'endTime',
                index: 'endTime',
                sortable: false,
                title: false,
                width: 150,
                align: 'center'
            },
            record_id: {
                name: "id",
                index: 'id',
                width: 80,
                title: false,
                sortable: false,
                align: 'center'
            },
            record_operate:{
                width: 200,
                title: false,
                sortable: false,
                align: 'center',
                formatter: function (v, o, r) {
                    return Zhibo.Util.formatter.record_operate(v, o, r);
                }
            }
        },

        TABLE_LIST: {
            localReader: {
                id: "channel_id",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            },
            multiselect: false,
            datatype: "local",
            height: 450,
            rowNum: 10,
            caption: "打点列表",
            colNames: ["id", "频道名称", "代号", "流地址", "服务器IP", "收费", "状态", "地区", "地区ID", "操作" ],
            colModel: ["channel_id", "channel_name", "channel_code", "channel_addr", "channel_ip", "freeType", "channel_status", "location", "loc_id", "operate2" ],
            pager: "#pager",
            onPaging: function (pgButton) {
                var retValue = Zhibo.Util.pageBeanPageHandler("list", "pager", Zhibo.Config.PageBean, pgButton);
                if (retValue != null) {
                    $("#list")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },
        TABLE_IP: {
            localReader: {
                id: "id",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            },
            multiselect: false,
            datatype: "local",
            height: 450,
            rowNum: 10,
            width: 600,
            colNames: ["ip", "地域", "操作"],
            colModel: ["ip", "region", "operate3"],
            pager: "#ip_pager",
            onPaging: function (pgButton) {
                var retValue = Zhibo.Util.pageBeanPageHandler("ipList", "ip_pager", Zhibo.Config.IpPageBean, pgButton);
                if (retValue != null) {
                    $("#ipList")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },

        TABLE_LOG: {
            url: Zhibo.urlConfig.logListFilterUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/vod/logList/filter");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 40,
            width: 875,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["ID", "操作时间", "人员", "动作", "备注"],
            colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
            pager: "#log_pager"
        },
        TABLE_RECORD: {
            url: Zhibo.urlConfig.recordListUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/vod/vodRecord/getList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 10,
            width: 875,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["ID", "开启收录时间", "停止收录时间", "创建人","添加时间","操作"],
            colModel: ['record_id', "record_start_time", "record_end_time" , "record_creator" , "log_addTime","record_operate"],
            pager: "#record_pager"
        },

        REGION_LIST: ['cq', 'sh', 'bj', 'tw'],
        REGION_CH_LIST: ['重庆', '上海', '北京', '台湾'],
        AUTH_REGION_CQ: false,
        AUTH_REGION_SH: false,
        AUTH_REGION_BJ: false,
        AUTH_REGION_TW: false,
        FUNC_EXTENT: ['enable', 'disable', 'delete_channel', 'modify_channel'],
        IP_LINK_AREA: {},
        AUTH_BASE: false,
        AUTH_SENIOR: false,
        monitorPlayer: null,
        PageBean: null,
        IpPageBean: null,
        ERROR_MSG: {
            CHANNEL_NAME_REG_ERROR: "频道名称格式不合法:名称由汉字、数字、字母组成",
            CHANNEL_CODE_REG_ERROR: '频道代码格式不合法:名称由字母、数字、"+ - _"组成',
            CHANNEL_ADDR_ILLEGAL_ERROR: "频道流地址格式不合法",
            CHANNEL_ADDR_PATTERN_ERROR: "流地址格式有误",
            CHANNEL_SERVER_EMPTY_ERROR: "频道服务器不能为空",
            RTMP_ERROR: "rtmp预览流地址格式不合法"
        },

        ENCODE_TYPE: ['CPU编码', 'GPU编码'],
        ENCODE_INDEX: ['GPU0', 'GPU1', 'GPU2', 'GPU3', 'GPU4'],
        ANSWER: ['否', '是'],
        ENCODE_PANOTYPE: ['', '否', '360度全景', '180度全景'],
        VOD_LOG_TYPE: {
            addElement: 101,
            delElement: 102,
            modifyElement: 103,
            includeElement: 104,
            stopElement: 105
        },
        FUNC_EXTENT_LOG: {
            'enable': 104,
            'disable': 105,
            'delete_channel': 102,
            'modify_channel': 103
        },
        WAIT_ADD_DATA: null,
        WHITE_LIST_WRAP_ONLINE:[
            {ip:"10.6.5.129"},
            {ip:"10.5.192.7"},
            {ip:"10.5.192.103"},
            {ip:"10.6.5.128"},
		    {ip: "10.5.192.8"}
        ],
        WHITE_LIST_WRAP_DEV:[
            {ip: "10.5.192.6",cn:"视频包装"},
			
        ]
    });
    Zhibo.Config.GREY_MODE = {
        containsObj: function (obj) {
            obj = $.extend({}, {ip: "", cn: ""}, obj);
            var checkArr = Zhibo.Config.WHITE_LIST_WRAP_ONLINE;
            if (auth.dev()) {
                checkArr = Zhibo.Config.WHITE_LIST_WRAP_DEV
            }
            var inRange = false;
            $.each(checkArr, function (i, element) {
                if(obj.ip == element.ip  ){
                    inRange = true;
                    return false;
                }
            })
            return inRange;
        }
    }
});
define(
    '../zhibo/Zhibo.Dao',['require','exports','module'],function (require, exports, module) {
        Zhibo.Dao = $.extend({}, EpgWeb.Dao, {
            cfgName: {
                getSourceIp: "getSourceIp",
                LogType: "vod_log"
            },
            getList: function (data, callback) {
                var options = {
                    type: "get",
                    url: Zhibo.urlConfig.channelUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            getIpList: function (data, callback) {
                var options = {
                    type: "get",
                    url: Zhibo.urlConfig.machinemodifyUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            modifyChannel: function (data, callback) {
                var options = {
                    type: "post",
                    url: Zhibo.urlConfig.modifyUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            addChannel: function (data, callback) {
                var options = {
                    type: "post",
                    url: Zhibo.urlConfig.channelUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            IpModify: function (data, callback) {
                var options = {
                    type: "post",
                    url: Zhibo.urlConfig.machinemodifyUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            dotLoad: function (data, callback) {
                var url = Zhibo.urlConfig.dotLoadUrl.replace("@ipServer", $("#ip").val());
                var options = {
                    type: "get",
                    url: url,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            version: function (data, callback) {
                var url = Zhibo.urlConfig.versionUrl.replace("@ipServer", $("#ip").val());
                var options = {
                    type: "get",
                    url: url,
                    dataType: "text",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            channelInfo: function (data, callback) {
                var url = Zhibo.urlConfig.channelInfoUrl.replace("@ipServer", $("#ip").val());
                var options = {
                    type: "get",
                    url: url,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            submitLogEntity: function (data, callback) {
                var url = Zhibo.urlConfig.submitLogUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(data)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/vod/saveLog");
            },
            logType: function () {
                return this.getDataByName(this.cfgName.LogType);
            },
            getSourceIp: function () {
                return this.getDataByName(this.cfgName.getSourceIp);
            },
            // 开始 收录任务相关
            delRecord:function(data, callback){
                var options = {
                    type: "post",
                    url: Zhibo.urlConfig.recordDelUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options,"/vod/vodRecord/del");
            },
            addRecord:function(data, callback){
                var options = {
                    type: "post",
                    url: Zhibo.urlConfig.recordAddUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options,"/vod/vodRecord/add");
            },
            editRecord:function(data, callback){
                var options = {
                    type: "post",
                    url: Zhibo.urlConfig.recordEditUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options,"/vod/vodRecord/edit");
            }
            // 结束 收录任务相关
        })
    }
);
define('../zhibo/Zhibo.Util',['require','exports','module'],function (require, exports, module) {
    Zhibo.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            channel_status: function (cellvalue, options, rowObject) {
                if (cellvalue == 1) {
                    return "收录中"
                } else if (cellvalue == null) {
                    return "错误";
                }
                return "未收录";
            },
            freeType: function (cellvalue, options, rowObject) {
                if (cellvalue == 1) {
                    return "是"
                }
                return "否"
            },
            channel_ip: function (cellvalue, options, rowObject) {
                if (cellvalue == null || Zhibo.Config.IP_LINK_AREA[cellvalue] == null) {
                    return "未知"
                }
                return Zhibo.Config.IP_LINK_AREA[cellvalue]
            },
            operate2: function (cellvalue, options, rowObject) {
                //收录/停止收录,打点,新打点,修改,加入预览,编码参数，编码详情,预置收录，定时开启,删除,日志
                var htmlArr = ["", "", "", "", "", "", "", "", "", "", "",""];
                var disabledValue = rowObject.channel_status === 0 ? 'disabled="disabled"' : ""
                var emptyValue = rowObject.channel_status === 0 ? "" : 'disabled="disabled"'
                if (Zhibo.Config.AUTH_BASE) {
                    htmlArr[4] = '<button onclick="Zhibo.Util.addMonitor(' + rowObject.channel_id + ')" type="button" rtmp="' + rowObject.rtmp + '" channel-id="' + rowObject.channel_id + '" class="btn btn-default addMonitor" ' + disabledValue + ' >加入预览</button>';
                    htmlArr[2] = '<button onclick="Zhibo.Util.addPointEPG2(' + rowObject.channel_id + ')" type="button" channel-id="' + rowObject.channel_id + '" class="btn btn-default pointer" ' + disabledValue + ' >新打点</button>';
                    if (Zhibo.Config.GREY_MODE.containsObj({ ip:rowObject.channel_ip })) {
                        htmlArr[11] = '<button onclick="Zhibo.Util.openWrapSys(' + rowObject.channel_id + ')" type="button" channel-id="' + rowObject.channel_id + '" class="btn btn-default pointer" ' + disabledValue + ' >包装系统</button>';
                    }
                }
                if (Zhibo.Config.AUTH_SENIOR) {
                    if (rowObject.hasOwnProperty('channel_status')) {
                        if (rowObject.channel_status === 0) {
                            htmlArr[0] = '<button type="button" onclick="Zhibo.Util.startRecord(' + rowObject.channel_id + ')" class="btn btn-default start_record" style="margin-left: 24px">收录</button>';
                        } else if (rowObject.channel_status === 1) {
                            htmlArr[0] = '<button type="button" onclick="Zhibo.Util.stopRecord(' + rowObject.channel_id + ')" class="btn btn-default stop_record">停止收录</button>';
                        }
                    }
                    htmlArr[3] = '<button onclick="Zhibo.Util.changeElement(' + rowObject.channel_id + ')" type="button" rtmp="' + rowObject.rtmp + '" class="btn btn-default change" ' + emptyValue + ' >修改</button>';
                    htmlArr[5] = '<button onclick="Zhibo.Util.jumpToCodeEdit(' + rowObject.channel_id + ')" type="button" class="btn btn-default modify-code-pram" ' + emptyValue + ' >编码参数</button>';
                    htmlArr[6] = '<button onclick="Zhibo.Util.showCodeDetail(\'' + rowObject.channel_ip + '\', \'' + rowObject.channel_code + '\')" type="button" class="btn btn-default modify-code-pram" >编码详情</button>';
                    //htmlArr[5] = '<a href="http://lego.iqiyi.com/live2VOD/preSet/home?channel_name=' + rowObject.channel_name + '&channel_id=' + rowObject.channel_id + '" target="_blank" style="margin-right:15px;" class="btn btn-default">预置收录</a>';
                    htmlArr[7] = '<a href="./live2VOD_preset_home.html?channel_name=' + rowObject.channel_name + '&channel_id=' + rowObject.channel_id + '" target="_blank" style="margin-right:15px;" class="btn btn-default">预置收录</a>';
                    htmlArr[9] = '<button onclick="Zhibo.Util.delElement(' + rowObject.channel_id + ')" type="button" class="btn btn-default del" ' + emptyValue + ' >删除</button>'
                    htmlArr[10] = '<button onclick="Zhibo.Util.openHistory(' + rowObject.channel_id + ')" type="button" class="btn btn-default history" >日志</button>'
                    htmlArr[8] = '<button onclick="Zhibo.Util.openRecord(' + rowObject.channel_id + ')" type="button" class="btn btn-default history" >定时收录</button>'
                }
                return htmlArr.join("");
            },
            region: function (cellvalue, options, rowObject) {
                var htmlArr = [];
                $.each(Zhibo.Config.REGION_CH_LIST, function (i, element) {
                    htmlArr.push("<option value='" + i + "' " + (i == cellvalue ? "selected='selected'" : "") + ">" + element + "</option>")
                })
                return '<select class="input-medium"><option value="">请选择</option>' + htmlArr.join("") + '</select>';
            },
            operate3: function (cellvalue, options, rowObject) {
                return '<button type="button" onclick="Zhibo.Util.IpModify(' + rowObject.id + ')">修改</button>|<button type="button" onclick="Zhibo.Util.IpDel(' + rowObject.id + ')">删除</button>';
            },
            log_type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Zhibo.Dao.logType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                return ret;
            },
            record_operate: function (cellvalue, options, rowObject) {
                return '<button type="button" onclick="Zhibo.Util.modifyRecord(' + rowObject.id + ')">编辑</button>|<button type="button" onclick="Zhibo.Util.delRecord(' + rowObject.id + ')">删除</button>';
            },
            log_descr: function (cellvalue, options, rowObject) {
                var ret = cellvalue;
                if (rowObject.type == 107 || rowObject.type == 108) {
                    try {
                        ret = Zhibo.Util.decodeDescription(cellvalue)
                    } catch (exception) {
                        console.log("has error ; rowObject.id  " + rowObject.id);
                        ret = cellvalue;
                    }
                }
                return  ret;
            }
        },
        setContainer: function ($container) {
            this.$container = $container;
        },
        startRecord: function (elementId) {
            SystemDialog.queryConfirm("是否确定要收录操作？", function (flag) {
                if (flag) {
                    var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
                    req_publicparams["func"] = "enable";
                    Zhibo.Util.modifyChannel(req_publicparams, elementId);
                }
            });
        },

        stopRecord: function (elementId) {
            SystemDialog.queryConfirm("是否确定要停止收录操作？", function (flag) {
                if (flag) {
                    var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
                    req_publicparams["func"] = "disable";
                    Zhibo.Util.modifyChannel(req_publicparams, elementId);
                }
            });
        },
        delElement: function (elementId) {
            SystemDialog.queryConfirm("是否确定要删除操作？", function (flag) {
                if (flag) {
                    var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
                    req_publicparams["func"] = "delete_channel";
                    Zhibo.Util.modifyChannel(req_publicparams, elementId);
                }
            });
        },
        addPointEPG: function (elementId) {
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/epg/dadian.html?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], "epg" + req_publicparams['channel_code']);
        },
        addPointEPG2: function (elementId) {
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/epg/dadian_news_merge.html?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], "epg" + req_publicparams['channel_code']);
        },

        addPoint: function (elementId) {
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/peditor/home_epg?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], req_publicparams['channel_code']);
        },
        buildPublicParams: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            var publicParams = {
                "src_channel_ip": selectElement.channel_ip,
                "channel_ip": selectElement.channel_ip,
                "src_channel_addr": selectElement.channel_addr,
                "channel_addr": selectElement.channel_addr,
                "channel_name": selectElement.channel_name,
                "channel_code": selectElement.channel_code,
                "location": selectElement.location,
                "locationCategory": selectElement.loc_id,
                "freeType": selectElement.freeType,
                //   "index"				:	$.trim($("table#channel_list tr").index($(this).parents("tr"))),
                "type": $("#myTab li.active").attr("value"),
                "src_channel_code": selectElement.channel_code
            };

            return publicParams;
        },
        addChannel: function ($data) {
            if ($.isEmptyObject($data)) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "接口ADD_CHANNEL参数不能为空"})
                return;
            }
            $data['username'] = $("div.user a.name").html();
            $data['from_client'] = true;
            Zhibo.Dao.addChannel($data, function (data) {
                if (data == null) {
                    EpgWeb.Plugin.showTips({"type": "error", "content": "/channel/modify 接口异常"})
                    return;
                }
                if (data.code != null && data.code == 200) {
                    if (parseInt(data['response']['status']) == 0) {
                        Zhibo.Config.WAIT_ADD_DATA = $data;
                        EpgWeb.Plugin.showTips({ "content": "success"});
                        $("button[name=channelQuery]").click();
                    } else {
                        EpgWeb.Plugin.showTips({"type": "error", "content": data['response']['error']})
                    }
                }
            });
        },
        modifyChannel: function ($data, elementId) {
            if ($data === undefined || $data == null || !$data.hasOwnProperty('func')) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "操作频道失败:参数不完整"})
                return;
            }
            if (-1 == $.inArray($data['func'], Zhibo.Config.FUNC_EXTENT)) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "操作频道失败:" + $data['func'] + "方法不支持"});
                return;
            }
            $data['username'] = $("div.user a.name").html();
            $data['from_client'] = true;
            Zhibo.Dao.modifyChannel($data, function (data) {
                var modifyResult = {result: "log error"}
                if (data == null) {
                    EpgWeb.Plugin.showTips({"type": "error", "content": "/channel/modify 接口异常"});
                    modifyResult.result = "log error,data is null!";
                } else if (data.code != null && data.code == 200) {
                    if (parseInt(data['response']['status']) == 0) {
                        EpgWeb.Plugin.showTips({ "content": "success"});
                        $("button[name=channelQuery]").click();
                        modifyResult.result = "success";
                        if ($data['func'] == "delete_channel") {

                            Zhibo.Util.delRecordTrigger(parseInt(elementId));
                        }
                    } else {
                        EpgWeb.Plugin.showTips({"type": "error", "content": data['response']['error']})
                        modifyResult.result = "log error:" + data['response']['error'];
                    }
                } else {
                    modifyResult.result = "log error code :" + data.code;
                }
                Zhibo.Util.doSubmitLogEntity({ channelId: elementId, descr: modifyResult.result + "|" + JSON.stringify($data), type: Zhibo.Config.FUNC_EXTENT_LOG[$data['func']] })
            });
        },

        getSelectElement: function (elementId) {
            return Zhibo.Config.PageBean.findData("channel_id", elementId)
        },
        getSelectIpElement: function (elementId) {
            return Zhibo.Config.IpPageBean.findData("id", elementId)
        },

        changeElement: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            if (selectElement != null) {
                var targetDiv = $("#modifyDiv");
                targetDiv.dialog("open");
                targetDiv.find("input[name=act_type]").val("modify");
                targetDiv.find("input[name=channel_code]").val($.trim(selectElement.channel_code));
                targetDiv.find("input[name=channel_name]").val($.trim(selectElement.channel_name));
                targetDiv.find("input[name=channel_code]").attr("readonly", "readonly");
                targetDiv.find("input[name=channel_addr]").val($.trim(selectElement.channel_addr));
                targetDiv.find("input[name=channel_addr]").attr("readonly", "readonly");
                targetDiv.find("input[name=rtmp]").val($.trim(selectElement.rtmp));
                targetDiv.find("input[name=location]").val($.trim(selectElement.location));
                targetDiv.find("input[name=location]").attr("data-id", $.trim(selectElement.loc_id));
                targetDiv.find("input[name=freeType][value=" + selectElement.freeType + "]").prop("checked", true);
                var regValue = Zhibo.Config.IP_LINK_AREA[selectElement.channel_ip].substr(selectElement.channel_ip.length).replace(/[\[|\]]/g, "");
                if (Zhibo.Config.REGION_LIST.indexOf(regValue) != -1) {
                    targetDiv.find("select[name=server_region2]").val(Zhibo.Config.REGION_LIST.indexOf(regValue));
                    targetDiv.find("select[name=server_region2]").change();
                }
                targetDiv.find("select[name=sourceiplist]").val(selectElement.channel_ip);
                targetDiv.find("input[name=channel_id]").val(selectElement.channel_id);
            }
        },
        addMonitor: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            var key = 'monitor', params = {};
            params['id'] = selectElement.channel_id;
            params['name'] = selectElement.channel_name;
            params['rtmp'] = selectElement.rtmp;
            if (!$.trim(params['rtmp'])) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "请填写正确的rtmp流地址"})
                return;
            }
            var dotUrl = 'http://lego.iqiyi.com/peditor/home3?' + selectElement['channel_code'] + '=' + selectElement['channel_ip'] + '&free_type=' + selectElement.freeType + '&channel_id=' + selectElement.channel_id;
            params['dotUrl'] = dotUrl;
            try {
                var monitorArr = Zhibo.Util.Storage.getItem(key);
                if (monitorArr) {
                    if (monitorArr.length > 11) {
                        EpgWeb.Plugin.showTips({type: "error", "content": "12个频道已经添加满"})
                        return;
                    }
                    for (var i in monitorArr) {
                        if (monitorArr[i]['id'] == params['id']) {
                            monitorArr.splice(i, 1);
                            break;
                        }
                    }
                } else {
                    monitorArr = [];
                }
                monitorArr.unshift(params);
                Zhibo.Util.Storage.setItem(key, monitorArr);
                Zhibo.Util.openMonitorPlayer();
                EpgWeb.Plugin.showTips({ "content": "视频监控添加成功"})
            } catch (e) {
                EpgWeb.Plugin.showTips({"type": "error", "content": e.name + ": " + e.message})
            }
        },
        jumpToCodeEdit: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            var webUrl = 'http://' + $.trim(selectElement.channel_ip) + ':8080/channel?from_client=true&show=1';
            webUrl += '&channel_code=' + $.trim(selectElement.channel_code);
            webUrl += '&channel_addr=' + $.trim(selectElement.channel_addr);
            window.open(webUrl);
        },

        showCodeDetail: function (ip, code) {
            $("#ip").val(ip);
            $("#code").val(code);
            $("#codeDetail").dialog("open");
        },

        addElement: function () {
            $("#modifyDiv").dialog("open");
            $("#modifyDiv").find("input[name=act_type]").val("add");
        },
        _initEditEvent: function () {
            var self = this;
        },
        getModifyData: function (targetDiv) {
            var obj = {};
            obj.channelName = $.trim(targetDiv.find("input[name=channel_name]").val());
            obj.channelCode = $.trim(targetDiv.find("input[name=channel_code]").val());
            obj.channelAddr = $.trim(targetDiv.find("input[name=channel_addr]").val());
            obj.location = $.trim(targetDiv.find("input[name=location]").val());
            obj.loc_id = $.trim(targetDiv.find("input[name=location]").attr("data-id"));
            if ($.isEmptyObject(obj.location)) {
                obj.loc_id = -1;
            }
            obj.rtmp = $.trim(targetDiv.find("input[name=rtmp]").val());
            obj.serverName = targetDiv.find("select[name=sourceiplist]").val();
            obj.freeType = targetDiv.find("input[name=freeType]:checked").val();
            return obj;
        },

        saveModify: function () {
            var targetDiv = $("#modifyDiv");
            var act_type = targetDiv.find("input[name=act_type]").val();
            var obj = Zhibo.Util.getModifyData(targetDiv);
            var checkArr = [];
            checkArr.push({value: obj.channelName, error: Zhibo.Config.ERROR_MSG.CHANNEL_NAME_REG_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                var rule = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
                return rule.test(checkValue);
            }   })
            checkArr.push({value: obj.channelCode, error: Zhibo.Config.ERROR_MSG.CHANNEL_CODE_REG_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                var code_rule = /^[A-Za-z0-9\+_-]+$/;
                return code_rule.test(checkValue);
            }   })
            checkArr.push({value: obj.channelAddr, error: Zhibo.Config.ERROR_MSG.CHANNEL_ADDR_ILLEGAL_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                return checkValue.match(/((^rtmp)|(^RTMP)|(^udp)|(^UDP)|(http)|(HTTP)|(^udi)|(^UDI)):\/\//g) != null;
            }   })
            checkArr.push({value: obj.channelAddr, error: Zhibo.Config.ERROR_MSG.CHANNEL_ADDR_PATTERN_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                if (( checkValue.match(/((^udp)|(^UDP)):\/\//g) != null | checkValue.match(/((^udi)|(^UDI)):\/\//g) != null ) && checkValue.split(':').length > 3) {
                    return false;
                }
                return true;
            } });
            checkArr.push({value: obj.serverName, error: Zhibo.Config.ERROR_MSG.CHANNEL_SERVER_EMPTY_ERROR, type: "not_empty"});

            if (obj.rtmp.length > 0) {
                checkArr.push({value: obj.rtmp, error: Zhibo.Config.ERROR_MSG.RTMP_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                    return checkValue.match(/((^rtmp)|(^RTMP)):\/\//g) != null
                }})

            }
            if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                return;
            }

            var $req_params = {
                "channel_name": obj.channelName,
                "channel_code": obj.channelCode,
                "channel_addr": obj.channelAddr,
                "channel_ip": obj.serverName,
                "location": obj.location,
                "loc_id": obj.loc_id,
                "type": $("#myTab li.active").attr("value"),
                "freeType": obj.freeType
            };
            if (obj.rtmp.length > 0) {
                $req_params['rtmp'] = obj.rtmp;
            }
            if (act_type == "add") {
                Zhibo.Util.addChannel($req_params)
            } else if (act_type == "modify") {
                var elementId = targetDiv.find("input[name=channel_id]").val();
                var selectElement = Zhibo.Util.getSelectElement(elementId);
                $req_params['src_channel_ip'] = selectElement.channel_ip;
                $req_params['src_channel_addr'] = selectElement.channel_addr;
                $req_params['src_channel_code'] = selectElement.channel_code;
                $req_params['func'] = 'modify_channel';
                Zhibo.Util.modifyChannel($req_params, elementId)
            }
            targetDiv.dialog("close");
        },
        cancelModify: function () {
            $("#modifyDiv").dialog("close");
        },

        IpModify: function (ipDataId) {
            var ipData = Zhibo.Util.getSelectIpElement(ipDataId);
            var area = $("#ipControlForm tr#" + ipData.id + " select").val();
            if (area.length == 0) {
                EpgWeb.Plugin.showTips({type: "error", content: "区域不能为空"});
                return
            }
            Zhibo.Dao.IpModify({"func": "modify", "type": $("#myTab li.active").attr("value"), "ip": ipData.ip, area: parseInt(area)}, function (data) {
                if (data != null && data.code == 200) {
                    EpgWeb.Plugin.showTips({ content: "success"});
                } else {
                    EpgWeb.Plugin.showTips({type: "error", content: data.response.error});
                }
                $("#ip-list").click();
            });
        },
        IpDel: function (ipDataId) {
            SystemDialog.queryConfirm("确认要删除ip么？", function (flag) {
                if (flag) {
                    var ipData = Zhibo.Util.getSelectIpElement(ipDataId);
                    Zhibo.Dao.IpModify({"func": "del", "type": $("#myTab li.active").attr("value"), "ip": ipData.ip}, function (data) {
                        if (data != null && data.code == 200) {
                            EpgWeb.Plugin.showTips({ content: "success"});
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: data.response.error});
                        }
                        $("#ip-list").click();
                    });
                }
            })
        },
        IpAdd: function () {
            var newIpValue = $.trim($("input[name=newIp]").val());
            if (newIpValue.length == 0) {
                EpgWeb.Plugin.showTips({type: "error", content: "ip不能为空"});
                return
            }
            var regIps = /^(((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|[0-9])\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|[0-9]))$/
            var hasError = false;
            if (regIps.test(newIpValue)) {
                var ipArr = newIpValue.split(".");
                var newIpArr = [];
                $.each(ipArr, function (i, element) {
                    newIpArr.push(parseInt(element))
                })
            } else {
                hasError = true;
            }
            if (hasError) {
                EpgWeb.Plugin.showTips({type: "error", content: "ip格式不合法"});
                return;
            }
            newIpValue = newIpArr.join(".");

            var sendData = {"func": "add", "type": $("#myTab li.active").attr("value"), "ip": newIpValue, "area": ""};
            var jsonData = Zhibo.Config.IpPageBean.findData("ip", newIpValue);
            if (jsonData != null) {
                EpgWeb.Plugin.showTips({type: "error", content: "ip已存在"});
                return;
            }

            Zhibo.Dao.IpModify(sendData, function (data) {
                $("input[name=newIp]").val("");
                if (data != null && data.code == 200) {
                    EpgWeb.Plugin.showTips({ content: "success"});
                } else {
                    EpgWeb.Plugin.showTips({type: "error", content: data.response.error});
                }
                $("#ip-list").click();
            });
        },
        openMonitorPlayer: function (btn) {
            //判断是否打开
            if (Zhibo.Config.monitorPlayer == null || Zhibo.ConfigmonitorPlayer.closed) {
                //live2VOD_livelist_monitor
                //http://lego.iqiyi.com/live2VOD/liveList/monitor
                Zhibo.ConfigmonitorPlayer = window.open("/epg/live2VOD_livelist_monitor.html", "openMonitorPlayer");
            }
            else if (btn) {
                Zhibo.Config.monitorPlayer.focus();
            }
        },

        modifyRecord: function (entityId) {
            var arr = $("#recordList").getData();
            var selectElement = null;
            $.each(arr, function (i, element) {
                if (element.id == entityId) {
                    selectElement = element;
                    return false;
                }
            })
            this.cleanRecordForm();
            if (selectElement != null) {
                $('input[name=record_entity_id]').val(entityId);
                $("button[name=record-add]").hide();
                $("button[name=record-edit]").show();
                $("input[name=record_start_time]").datetimepicker("setDate", new Date(selectElement.startTime.replace(/-/g, "/")));
                if (selectElement.endTime != null) {
                    $("input[name=record_end_time]").datetimepicker("setDate", new Date(selectElement.endTime.replace(/-/g, "/")));
                }
                if ((selectElement.notifyType & 1) == 1) {
                    $("input[name=notify_type][value='1']").prop("checked", true);
                }
                if ((selectElement.notifyType & 2) == 2) {
                    $("input[name=notify_type][value='2']").prop("checked", true);
                }
                if ((selectElement.notifyType & 4) == 4) {
                    $("input[name=notify_type][value='4']").prop("checked", true);
                }
                if (selectElement.projectWorkers != null && selectElement.projectWorkers.length > 2) {
                    var workerArr = JSON.parse(selectElement.projectWorkers);
                    $.each(workerArr, function (i, element) {
                        $("input[name=project_workers]").suggest("addValue", element);
                    })
                }
            }
        },
        editRecord: function () {
            var sendData = this.prepareRecordData();
            if (sendData == null) {
                return;
            }
            var entityId = Number($('input[name=record_entity_id]').val());
            var arr = $("#recordList").getData();
            var selectElement = null;
            $.each(arr, function (i, element) {
                if (element.id == entityId) {
                    selectElement = element;
                    return false;
                }
            });
            selectElement.startTime = sendData.startTime;
            selectElement.projectWorkers = sendData.projectWorkers;
            selectElement.notifyType = sendData.notifyType;
            if (sendData.endTime != null) {
                selectElement.endTime = sendData.endTime;
            }
            Zhibo.Dao.editRecord({data: JSON.stringify(selectElement)}, function (data) {
                if (data != null && data.code == "A00000") {
                    EpgWeb.Plugin.showTips({ content: "修改成功"});
                    Zhibo.Util.cleanRecordForm();
                    $('#recordList').jqGrid('setGridParam', {
                        page: 1
                    }).trigger('reloadGrid');
                } else {
                    EpgWeb.Plugin.showTips({ type: "error", content: "修改失败" + (  data != null ? ":" + data.msg : "" )});
                }
            })
        },
        delRecordTrigger: function (channelId) {
            console.log("start delRecordTrigger ")
            var sendData = {"channelId": channelId};
            Zhibo.Dao.delRecord(sendData, function (data) {
                if (data != null && data.code == "A00000") {
                    console.log("end delRecordTrigger success")
                } else {
                    console.log("end delRecordTrigger fail")
                }
            })
        },
        delRecord: function (entityId) {
            var channelId = parseInt($("input[name=record_channel_id]").val());
            var sendData = {"channelId": channelId};
            if (entityId != null) {
                sendData.taskId = entityId
            }
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Zhibo.Dao.delRecord(sendData, function (data) {
                        if (data != null && data.code == "A00000") {
                            var recordEntityId = Number($('input[name=record_entity_id]').val());
                            if (recordEntityId == entityId) {
                                Zhibo.Util.cleanRecordForm();
                            }
                            EpgWeb.Plugin.showTips({ content: "删除成功"});
                            $('#recordList').jqGrid('setGridParam', {
                                page: 1
                            }).trigger('reloadGrid');
                        } else {
                            EpgWeb.Plugin.showTips({ type: "error", content: "删除失败" + (  data != null ? ":" + data.msg : "" )});
                        }
                    })
                }
            })
        },
        addRecord: function () {
            var channelId = parseInt($("input[name=record_channel_id]").val());
            var sendData = this.prepareRecordData();
            if (sendData == null) {
                return;
            }
            sendData.channelId = channelId;
            Zhibo.Dao.addRecord({data: JSON.stringify(sendData)}, function (data) {
                if (data != null && data.code == "A00000") {
                    EpgWeb.Plugin.showTips({ content: "添加成功"});
                    Zhibo.Util.cleanRecordForm();
                    $('#recordList').jqGrid('setGridParam', {
                        page: 1
                    }).trigger('reloadGrid');
                } else {
                    EpgWeb.Plugin.showTips({ type: "error", content: "添加失败" + (  data != null ? ":" + data.msg : "" )});
                }
            })
        },
        prepareRecordData: function () {
            var startTime = $("input[name=record_start_time]").val().trim();
            var endTime = $("input[name=record_end_time]").val().trim();
            var workersArr = $("span.qui-tag");
            var newDataArr = [];
            if (workersArr.length > 0) {
                $.each(workersArr, function (i, element) {
                    newDataArr.push({ id: $(element).attr("data-tag-id"), label: $(element).attr("data-tag-label") });
                })
            }
            var notifyTypeArr = $("input[name=notify_type]:checked");
            var notifyType = 0;
            if (notifyTypeArr.length > 0) {
                $.each(notifyTypeArr, function (i, element) {
                    notifyType += parseInt($(element).val());
                })
            }
            if (newDataArr.length > 0 && notifyType == 0) {
                EpgWeb.Plugin.showTips({ type: "error", content: "请选择通知方式"});
                return null;
            }
            if (!EpgWeb.Plugin.Validate.checkDateFormat(startTime)) {
                EpgWeb.Plugin.showTips({ type: "error", content: "开始时间格式错误"});
                return null;
            }
            var sendData = { "startTime": startTime, "projectWorkers": JSON.stringify(newDataArr), notifyType: notifyType};
            if (endTime.length > 0) {
                if (!EpgWeb.Plugin.Validate.checkDateFormat(endTime)) {
                    EpgWeb.Plugin.showTips({ type: "error", content: "结束时间格式错误"});
                    return null;
                }
                sendData.endTime = endTime;
            }
            return sendData;
        },

        cleanRecordForm: function () {
            $("input[name=record_start_time]").val("");
            $("input[name=record_end_time]").val("");
            $("button[name=record-add]").show();
            $("button[name=record-edit]").hide();
            $('input[name=record_entity_id]').val("");
            $('input[name=project_workers]').val("");
            $("a.qui-tag-remove").click();
            $("input[name=notify_type]:checked").click()
        },
        Storage: {
            setItem: function (k, v) {
                var strValue = JSON.stringify(v);
                localStorage.setItem(k, strValue);
            },
            removeItem: function (k) {
                localStorage.removeItem(k);
            },
            getItem: function (k) {
                return JSON.parse(localStorage.getItem(k));
            }
        },
        openHistory: function (entityId) {
            $("#vodLogDiv").dialog("open");
            $('#logList').jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: { paramsObj: JSON.stringify({ EQI_channelId: entityId}) }
            }).trigger('reloadGrid');
        },
        openRecord: function (entityId) {
            $("#vodRecordDiv").dialog("open");
            this.cleanRecordForm();
            $('input[name=record_channel_id]').val(entityId);
            $('#recordList').jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: {channelId: entityId}
            }).trigger('reloadGrid');
        },
        submitAddLog: function (dataArr, waitData) {
            $.each(dataArr, function (i, entity) {
                if (waitData.channel_code == entity.channel_code && waitData.channel_ip == entity.channel_ip) {
                    waitData.channel_id = entity.channel_id;
                    var submitLogData = { channelId: waitData.channel_id, type: Zhibo.Config.VOD_LOG_TYPE.addElement, descr: "suc|" + JSON.stringify(waitData) };
                    Zhibo.Util.doSubmitLogEntity(submitLogData);
                    return true;
                }
            })
        },
        doSubmitLogEntity: function (submitLogData) {
            Zhibo.Dao.submitLogEntity(submitLogData, function (data) {
                    if (data == null || data.code != "A00000") {
                        console.warn("submitLogEntity error");
                    } else {
                        console.log("submitLogEntity suc");
                    }
                }
            )
        },
        decodeDescription: function (description) {
            var elementArr = description.split("|");
            var newArr = [];
            if (elementArr.length == 2) {
                newArr.push(elementArr.shift());
            } else if (elementArr.length >= 3) {
                newArr.push(elementArr.shift());
                newArr.push(elementArr.shift());
            }
            var jsonObj = JSON.parse(elementArr.join("|"));
            var list = JSON.parse(jsonObj.list);
            if( list.length > 2){
                var newFold = [];
                var nodeStart = -100;
                var nodeEnd = -100;
                var curIndex = 0;
                $.each(list, function (i, element) {
                    curIndex = element;
                    if (curIndex > nodeEnd + 1) {
                        if (nodeStart >= 0) {
                            newFold.push({ start: nodeStart, end: nodeEnd});
                        }
                        nodeStart = curIndex;
                        nodeEnd = curIndex;
                    } else if (curIndex == nodeEnd + 1) {
                        nodeEnd = curIndex;
                    }
                })
                if (nodeEnd >= nodeStart) {
                    newFold.push({ start: nodeStart, end: nodeEnd});
                }
                jsonObj.list = newFold;
            }
            newArr.push(JSON.stringify(jsonObj));
            return newArr.join("|");
        },
        openWrapSys:function(elementId){
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/epg/dadian_wrap_sys.html?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], "epg_wrap" + req_publicparams['channel_code']);

        }
    });
});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Zhibo.Task.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../zhibo/Zhibo.Task',['require','exports','module'],function (require, exports, module) {
        Zhibo.Task = $.extend({}, EpgWeb.Task, {
            getLogType:function(taskName){
                var self = this;
                return self.getConfigType(taskName)
            },
            getSourceIp: function (username, regName) {
                var self = this;
                var handler = function (data) {
                    var parent1JDom = $("select[name=server_region]");
                    var parent2JDom = $("select[name=server_region2]");
                    var hasDataRegion = [];
                    var auth_region_arr = [Zhibo.Config.AUTH_REGION_CQ, Zhibo.Config.AUTH_REGION_SH, Zhibo.Config.AUTH_REGION_BJ , Zhibo.Config.AUTH_REGION_TW];

                    if (Zhibo.Config.AUTH_REGION_CQ && Zhibo.Config.AUTH_REGION_SH && Zhibo.Config.AUTH_REGION_BJ&& Zhibo.Config.AUTH_REGION_TW) {
                        $("<option>", {value: "all", html: "全部"}).appendTo(parent1JDom);
                    }

                    if (data != null && data.response != null && data.response.list) {
                        $.each(data.response.list, function (index, obj) {
                            if (hasDataRegion.indexOf(obj[1]) == -1) {
                                hasDataRegion.push(obj[1]);
                            }
                            Zhibo.Config.IP_LINK_AREA[obj[0]] = obj[0] + "[" + Zhibo.Config.REGION_LIST[obj[1]] + "]";
                        });
                        $.each(hasDataRegion, function (i, element) {
                            if (auth_region_arr[element]) {
                                $("<option>", {
                                    value: element,
                                    html: Zhibo.Config.REGION_CH_LIST[element]
                                }).appendTo(parent1JDom);
                                $("<option>", {
                                    value: element,
                                    html: Zhibo.Config.REGION_CH_LIST[element]
                                }).appendTo(parent2JDom);
                            }
                        })
                    } else {
                        console.log("wait to do");
                    }
                }
                var requestData = {url: Zhibo.urlConfig.machinelistUrl, type: "get",
                    params: {type: 0, area: 0, username: username, _: new Date().getTime(), from_client: true }
                };

                return {
                    regName: regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.redirect,
                        dataType: "json",
                        data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                        success: function (data) {
                            handler.call(this, data);
                        },
                        error: function (data) {
                            handler.call(this, data);
                        }
                    }
                }
            }
        })
    }
);
define(
    '../zhibo/Zhibo.Grid',['require','exports','module'],function (require, exports, module) {
        Zhibo.Grid = function (options) {
            this.dao = Zhibo.Dao;
            this.task = Zhibo.Task;
            this.config = Zhibo.Config;
            this.options = options || {};
        };
        Com.inherits(Zhibo.Grid, Ancestor.Grid).extend({
            runList: function (options, callback) {
                var self = this;
                self.initDialog();
                self.$grid = $('#list');
                self.$ipListGrid = $('#ipList');
                self.$logListGrid = $('#logList');
                self.$recordListGrid = $('#recordList');

                var taskArr = [];
                taskArr.push(self.task.getSourceIp($("div.user a.name").html(), this.dao.cfgName.getSourceIp));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
                self.initListGrid();
                self.initIpListGrid();
                self.initLogListGrid();
                self.initRecordListGrid();
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    console.log("load complete");
                    self.initAuthBaseView();
                    self.initAuthSeniorView();
                    self.initSuggest();
                    self.bindBasicEvent();
                    self.config.PageBean = Zhibo.Util.createPageBean();
                    self.config.IpPageBean = Zhibo.Util.createPageBean();
                    self.jumpFromZzd();
                    self.query();
                })
                self.initAuth();
            },
            jumpFromZzd:function () {
                var ip=location.search;
                var self =this;
                if(ip!="") {
                    ip = ip.slice(1).split("=")[1];
                    var exist = 0 ;
                    $("#QueryContainer").find("select[name=ip]").children().each(function(i,elem){
                        if($(elem).val() == ip){
                            exist=1;
                            $(elem).attr('selected',true)
                        };
                    });
                    if(exist==0){
                        $("#QueryContainer").find("select[name=ip]").append($('<option>').val(ip).html(ip).attr('selected',true));
                        self.showNoData(self.$grid);
                    }
                }
            },

            initAuth: function () {
                var self = this;
                self.readyCount = 0;
                self.finalCount = 6;
                self.initOver = false;
                auth.getAuthData({tips: 1, url: '/epg/auth/base'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_BASE = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/senior'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_SENIOR = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/cq'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_CQ = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/sh'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_SH = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/bj'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_BJ = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/region/tw'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_REGION_TW = true;
                    }
                    self.phaseOver();
                })
            },
            phaseOver: function () {
                var self = this;
                self.readyCount++;
                if (!self.initOver && self.readyCount == self.finalCount) {
                    self.initOver = true;
                    EpgWeb.ajaxQueue.startLoad();
                }
            },
            initAuthBaseView: function () {

            },
            initAuthSeniorView: function () {
                var self = this;
                if (self.config.AUTH_SENIOR) {
                    $("#auth_partner_div").show();
                    $("button[name=createBtn]").show();
                    $("button[name=ipControl]").show();
                } else {
                    $("#auth_partner_div").hide();
                    $("button[name=createBtn]").hide();
                    $("button[name=ipControl]").hide();
                }
            },

            getParam: function () {
                var params = {};
                params.username = $("div.user a.name").html();
                params.type = $("#myTab li.active").attr("value");
                var queryParent = $("#QueryContainer")
                if (queryParent.find("select[name=freeType]").val() != "all") {
                    params.freeType = $("select[name=freeType]").val()
                }
                if (queryParent.find("select[name=channel_status]").val() != "all") {
                    params.channel_status = $("select[name=channel_status]").val()
                }
                if (queryParent.find("select[name=ip]").val() != "all" && queryParent.find("select[name=ip]").val() != "all-limit") {
                    params.ip = $("select[name=ip]").val()
                }
                if (queryParent.find("input[name=channel_code]").val().length > 0) {
                    params.channel_code = $("input[name=channel_code]").val()
                }
                if (queryParent.find("input[name=channel_name]").val().length > 0) {
                    params.channel_name = $("input[name=channel_name]").val()
                }
                params.from_client = true;
                params._ = new Date().getTime();
                console.log(JSON.stringify(params));
                return params;
            },
            initListGrid: function (options, callback) {
                var self = this;
                // var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.$grid.jqGrid(options);
            },

            initIpListGrid: function (options, callback) {
                var self = this;
                //   var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_IP);
                options = $.extend(true, {}, gridConfig, options);
                self.$ipListGrid.jqGrid(options);
                $("#ip_pager_left").css({"width": "100px"})
            },

            initLogListGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LOG);
                var options = $.extend(true, {}, gridConfig);
                self.$logListGrid.jqGrid(options);
            },
            initRecordListGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_RECORD);
                var options = $.extend(true, {}, gridConfig);
                self.$recordListGrid.jqGrid(options);
            },
            showNoData: function (jqGridTarget) {
                var re_records = jqGridTarget.getGridParam('records');
                var parentElement = jqGridTarget.parent();
                var norecordElement = parentElement.find(".norecords")
                if (re_records == 0 || re_records == null) {
                    if (norecordElement.html() == null) {
                        parentElement.append('<div class="norecords">没有符合数据</div>');
                        norecordElement.hide();
                    }
                    norecordElement.show();
                } else {
                    norecordElement.hide();
                }
            },

            bindBasicEvent: function () {
                var self = this;
                $("button[name=createBtn]").bind("click", function (event) {
                    Zhibo.Util.addElement();
                })
                $("button[name=ipControl]").bind("click", function (event) {
                    $("#ipConfigDiv").dialog("open");
                })
                $("button[name=channelQuery]").bind("click", function (event) {
                    self.query();
                })
                $("#resetFrm").bind("click", function (event) {
                    $("form[name=basicFrm]")[0].reset();
                    $("select[name=server_region]").change();
                    //$("form[name=basicFrm]")
                })

                $("#ip-list").bind("click", function (event) {
                    self.ipQuery();
                })
                $("select[name=server_region]").bind("change", function (event) {
                    var selectJDom = $("#filter_source_ip");
                    selectJDom.html("");
                    var responseData = self.dao.getSourceIp();
                    var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                    if (null == eqVal) {
                        $("<option value='all'>全部</option>").appendTo(selectJDom);
                    } else {
                        $("<option value='all-limit'>全部</option>").appendTo(selectJDom);
                    }
                    if (responseData != null && responseData.response != null && responseData.response.list != null) {
                        $.each(responseData.response.list, function (i, obj) {
                            if (eqVal == null || eqVal == obj[1]) {
                                $("<option>", {
                                    value: obj[0],
                                    html: Zhibo.Config.IP_LINK_AREA[obj[0]]
                                }).appendTo(selectJDom);
                            }
                        })
                    }
                })
                $("select[name=server_region]").change();
                $("select[name=server_region2]").bind("change", function (event) {
                    var selectJDom = $("#sourceiplist")
                    selectJDom.html("");
                    var responseData = self.dao.getSourceIp();
                    var eqVal = event.currentTarget.value == "all" ? null : parseInt(event.currentTarget.value);
                    if (eqVal == null) {
                        $("<option value=''>请选择</option>").appendTo(selectJDom);
                    }
                    if (responseData != null && responseData.response != null && responseData.response.list != null) {
                        $.each(responseData.response.list, function (i, obj) {
                            if (eqVal == null || eqVal == obj[1]) {
                                $("<option>", {
                                    value: obj[0],
                                    html: Zhibo.Config.IP_LINK_AREA[obj[0]]
                                }).appendTo(selectJDom);
                            }
                        })
                    }
                })
                $("select[name=server_region2]").change();
            },

            query: function () {
                var self = this;
                self.dao.getList(self.getParam(), function (data) {
                    var retValue = null;
                    if (data.code === 200 && data.response != null && data.response.list != null) {
                        if (self.config.WAIT_ADD_DATA != null) {
                            var waitData = self.config.WAIT_ADD_DATA;
                            self.config.WAIT_ADD_DATA = null;
                            Zhibo.Util.submitAddLog(data.response.list, waitData);

                        }
                        if ($("select[name=ip]").val() == "all-limit") {
                            self.config.PageBean.setNewData(self.doRegionFilter(data.response.list));
                        } else {
                            self.config.PageBean.setNewData(data.response.list);
                        }

                    } else {
                        self.config.PageBean.setNewData([]);
                    }
                    retValue = self.config.PageBean.getCur();
                    self.$grid[0].addJSONData(retValue)
                    self.showNoData(self.$grid);
                });
            },
            doRegionFilter: function (dataArr) {
                var regionValue = Zhibo.Config.REGION_LIST[ parseInt($("select[name=server_region]").val())];
                var areaSign = null;
                var newArr = [];
                $.each(dataArr, function (i, element) {
                    areaSign = Zhibo.Config.IP_LINK_AREA[ element.channel_ip ]
                    if (areaSign != null && areaSign.indexOf(regionValue) != -1) {
                        newArr.push(element)
                    }
                })
                return newArr;
            },
            ipQuery: function () {
                var self = this;
                self.dao.getIpList({type: $("#myTab li.active").attr("value"), area: ""}, self.fillIpTable);
            },
            recordQuery: function () {
                var self = this;
                var channelId = $("input[name=record_channel_id]").val();
                self.$recordListGrid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {channelId: parseInt(channelId)}
                }).trigger("reloadGrid");
            },
            initDialog: function () {
                var self = this;
                $("#modifyDiv").dialog({
                    title: "打点项目明细",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $("#modifyDiv").find("form").trigger("reset");
                        $("#modifyDiv").find("input[name=channel_code]").removeAttr("readonly");
                        $("#modifyDiv").find("input[name=channel_addr]").removeAttr("readonly");
                        $("#modifyDiv").find("select[name=server_region2]").change();
                    }
                });

                $("#ipConfigDiv").dialog({
                    title: "ip分组管理",
                    autoOpen: false,
                    width: 700,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $('#ipConfigDiv').show();
                        self.ipQuery();
                    }
                });

                $("#codeDetail").dialog({
                    title: "编码详情",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $('#codeDetail').show();
                        self.fillCodeDetail();
                    }
                });

                $("#vodLogDiv").dialog({
                    title: "历史记录",
                    autoOpen: false,
                    width: 900,
                    height: 600,
                    modal: true,
                    dialogClass: 'alert'
                });
                self.initRecordDlg();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },

            initRecordDlg: function () {
                var self = this;
                $("#vodRecordDiv").dialog({
                    title: "定时收录设定",
                    autoOpen: false,
                    width: 900,
                    height: 600,
                    modal: true,
                    dialogClass: 'alert'
                });
                EpgWeb.Util.bindDate("record_start_time", "record_end_time");
                $("button[name=record-list]").on("click", function (event) {
                    self.recordQuery();
                })
                $("button[name=record-clear-list]").on("click", function (event) {
                    Zhibo.Util.delRecord();
                })
                $("button[name=record-clear-form]").on("click", function (event) {
                    Zhibo.Util.cleanRecordForm();
                })
            },

            initSuggest: function () {
                var locationSuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {types: "province,city", domestic: 1} : {word: term, types: "province,city", domestic: 1};
                            var requestData = {url: "http://lego.iqiyi.com/suggest/location-type", type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                $("input[name=location]").suggest(locationSuggest.options);

                var emailSuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Zhibo.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["email"];
                                itemData[options.labelKey] = item["userName"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=project_workers]").suggest(emailSuggest.options);
            },
            fillIpTable: function (data) {
                var jqGrid = $("#ipList");
                if (data.code === 200 && data.response != null && data.response.list != null) {
                    var formatterData = [];
                    $.each(data.response.list, function (i, element) {
                        formatterData.push({ip: element[1], region: element[2], id: element[0]});
                    });
                    Zhibo.Config.IpPageBean.setNewData(formatterData);
                    jqGrid[0].addJSONData(Zhibo.Config.IpPageBean.getCur())
                }
            },
            fillCodeDetail: function () {
                var self = this;
                var $size = $("#size"),
                    $codeType = $("#codeType"),
                    $gpuPipeline = $("#gpuPipeline"),
                    $delog = $("#delog"),
                    $v720p = $("#v720p"),
                    $v1080p = $("#v1080p"),
                    $dolby = $("#dolby"),
                    $panoType = $("#panoType"),
                    $zhiboVersion = $("#zhiboVersion"),
                    $bianmaqiVersion = $("#bianmaqiVersion");

                this.dao.version({}, function (data) {
                    if (data != null) {
                        var versions = data.split("|");
                        $zhiboVersion.val(versions[0]);
                        $bianmaqiVersion.val(versions[1]);
                    }
                });

                this.dao.channelInfo({from_client: "true", channel_code: $("#code").val()}, function (data) {
                    if (data != null) {
                        var info = data[0];
                        $size.val(info.dpi);
                        $codeType.val(Zhibo.Config.ENCODE_TYPE[info.encode_type]);
                        if (info.encode_type == 1) {
                            $('#gpuDiv').css('display', 'block');
                            $gpuPipeline.val(Zhibo.Config.ENCODE_INDEX[info.encode_index]);
                        } else {
                            $('#gpuDiv').css('display', 'none');
                            $gpuPipeline.val('');
                        }
                        $delog.val(Zhibo.Config.ANSWER[info.delog]);
                        $v720p.val(Zhibo.Config.ANSWER[info.v720p]);
                        $v1080p.val(Zhibo.Config.ANSWER[info.v1080p]);
                        $dolby.val(Zhibo.Config.ANSWER[info.dolby]);
                        $panoType.val(Zhibo.Config.ENCODE_PANOTYPE[info.panoType]);
                    }
                });

                this.dao.dotLoad({from_client: "true", channel_code: $("#code").val()}, function (data) {
                    if (data != null) {
                        var load = data.load;
                        var lavg_1 = load.lavg_1,
                            lavg_5 = load.lavg_5,
                            lavg_15 = load.lavg_15,
                            cpu = load.CPU,
                            K1 = load.K1;
                        var warnning = "<span style='color:#F00'>@warnning</span>";
                        var html = "CPU核数:" + cpu;
                        html += "</br>一分钟负载:";
                        if (parseInt(lavg_1) >= parseInt(cpu)) {
                            html += warnning.replace("@warnning", lavg_1);
                        } else {
                            html += lavg_1;
                        }
                        html += "</br>五分钟负载:";
                        if (parseInt(lavg_5) >= parseInt(cpu)) {
                            html += warnning.replace("@warnning", lavg_5);
                        } else {
                            html += lavg_5;
                        }
                        html += "</br>十五分钟负载:";
                        if (parseInt(lavg_15) >= parseInt(cpu)) {
                            html += warnning.replace("@warnning", lavg_15);
                        } else {
                            html += lavg_15;
                        }
                        html += "</br>是否有K1卡:" + Zhibo.Config.ANSWER[K1];
                        $("#dotLoad").html(html);
                    }
                });
            }
        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../live2VOD/live2VOD',['require','exports','module'],function(require, exports, module) {
        window.live2VOD = window.live2VOD || {
            version: '1.0'
        };
        live2VOD.Constant = {
            baseApiUrl:(auth.dev() ? "http://10.23.70.33:7004/":"http://dot.live.qiyi.domain/"),
            thirdUrl_channel_type:"http://lego.iqiyi.com/suggest/operation",
            devMode: auth.dev()
        }

        live2VOD.urlConfig = (function () {
            var useUrl = live2VOD.Constant.baseApiUrl;
            var add = useUrl+"v1/partner/add";
            var modify=useUrl+"v1/partner/modify";
            var del=useUrl+"v1/partner/del";
            var find=useUrl+"v1/partner/find";
            return {
                addUrl:add,
                modifyUrl:modify,
                delUrl:del,
                findUrl:find
            }
        })()
    }
);
define(
    '../live2VOD/live2VOD.Action',['require','exports','module'],function (require, exports, module) {
        live2VOD.Action = (function () {
            var listGrid = null;
            var editForm = null;
            // 表格

            function listRun(){
                if (!listGrid) {
                    listGrid = new live2VOD.Grid($.extend(true, {
                        '$container': $('#QueryContainer'),
                        type: 0
                    }, {}));
                }
                listGrid.runList();
                console.log('list grid run');
            }

            function editRun(){
                if(editForm == null){
                    editForm = new live2VOD.Edit($.extend(true, {
                        '$form': $('form[role=form]')
                    }, {}));
                    editForm.init();
                }
                console.log(' editRun ');
            }

            return {
                listRun:listRun,
                editRun:editRun
            }
        })();
    }
);
///import js-src/lib/
///import js-src/com/
define('../live2VOD/live2VOD.Config',['require','exports','module'],function (require, exports, module) {
    live2VOD.Config = $.extend({}, Ancestor.Config, {

        TABLE_COLMODEL_CONFIG: {
            channelname: {
                name: "channelname",
                index: 'channelname',
                title: false,
                width: 80,
                sortable: false,
                align: "center"
            },
            channelalias: {
                name: "channelalias",
                index: 'channelalias',
                title: false,
                width: 140,
                sortable: false,
                align: "center"
            },
            channeltype: {
                name: "channeltype",
                index: 'channeltype',
                title: false,
                width: 140,
                sortable: false,
                align: "center",
                hidden: true
            },
            channeltypeShow: {
                name: "channeltypeShow",
                index: 'channeltypeShow',
                title: false,
                width: 140,
                sortable: false,
                align: "center"
            },

            ugcid: {
                name: "ugcid",
                index: 'ugcid',
                title: false,
                width: 110,
                sortable: false,
                align: "center"
            },
            ugcname: {
                name: "ugcname",
                index: 'ugcname',
                title: false,
                width: 110,
                sortable: false,
                align: "center"
            },
            qipuid: {
                name: "qipuid",
                index: 'qipuid',
                title: false,
                width: 135,
                sortable: false,
                align: "center"
            },
            ugcmsg: {
                name: "ugcmsg",
                index: 'ugcmsg',
                title: false,
                width: 135,
                sortable: false,
                align: "center"
            },
            ptype: {
                name: "ptype",
                index: 'ptype',
                title: false,
                width: 110,
                sortable: false,
                align: "center",
                formatter: function (v, o, r) {
                    return live2VOD.Util.formatter.toUpperCase(v, o, r);
                }
            },
            operate: {
                title: false,
                width: 105,
                sortable: false,
                formatter: function (v, o, r) {
                    return live2VOD.Util.formatter.operate(v, o, r);
                }
            }
        },
        TABLE_LIST: {
            localReader: {
                id: "qipuid",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            },
            multiselect: false,
            datatype: "local",
            height: 450,
            rowNum: 80,
            caption: "打点列表",
            colNames: ["电视台", "代号", "未格式化频道","频道", "关联UGC用户ID", "当前昵称", "分甘同味合作方ID", "分甘同味合作方", "节目类型", "操作" ],
            colModel: ["channelname", "channelalias", "channeltype", "channeltypeShow", "ugcid", "ugcname", "qipuid", "ugcmsg" , "ptype", "operate"],
            pager: "#pager",
            onPaging: function (pgButton) {
                var retValue = live2VOD.Util.pageBeanPageHandler("list", "pager", live2VOD.Config.PageBean, pgButton);
                if (retValue != null) {
                    $("#list")[0].addJSONData(retValue)
                }
                return "stop";
            }
        },
        PageBean: null,
        EDIT_VALIDATOR: {
            rules: {
                channelname: "required",
                channelalias:{
                    required:true,
                    selfReg:/^[A-Z0-9]+$/
                },
                ugcid: {
                    required:true,
                    digits: true
                },
                ugcname: "required",
                qipuid:  {
                    required:true,
                    digits: true
                },
                ugcmsg: "required"
            },
            messages: {
                channelname:{
                    required:"电视台不能为空"
                },
                channelalias:{
                    required:"代号不能为空"
                },
                ugcid:{
                    required:"关联UGC用户ID不能为空",
                    digits:"必须是整数"
                },
                ugcname:{
                    required:"当前昵称不能为空"
                },
                qipuid:{
                    required:"分甘同味合作方ID不能为空",
                    digits:"必须是整数"
                },
                ugcmsg:{
                    required:"分甘同味合作方不能为空"
                }
            }
        }
    })


});
define(
    '../live2VOD/live2VOD.Dao',['require','exports','module'],function (require, exports, module) {
        live2VOD.Dao = $.extend({}, EpgWeb.Dao, {
            cfgName:{
               // getSourceIp:"getSourceIp"
            },

            getChannelType:function(handler){
                var ajaxOptions={
                    type:"post",
                    url:EpgWeb.urlConfig.redirect,
                    dataType:"json",
                    data:  {"request": JSON.stringify({url:  live2VOD.Constant.thirdUrl_channel_type, type: "get", params:{size:100} , needCookie: true}), timeSign: new Date().getTime()},
                    success: function (data) {
                        var formatData = [];
                        $.each(data.data,function(i,element){
                            formatData.push({id:element.id,label:element.name,value:element.name})
                        })
                        handler(formatData);
                        console.log("renderPanel happen");
                    },
                    error:function(data){
                        console.log("error happen");
                    }
                };
                $.ajax(ajaxOptions)
            },
            getList: function (data, callback) {
                var options = {
                    type: "get",
                    url: live2VOD.urlConfig.findUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            delChannel:function(data,callback){
                var options = {
                    type: "get",
                    url: live2VOD.urlConfig.delUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            modifyChannel:function(data,callback){
                var options = {
                    type: "get",
                    url: live2VOD.urlConfig.modifyUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            addChannel:function(data,callback){
                var options = {
                    type: "get",
                    url: live2VOD.urlConfig.addUrl,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options);
            }
        })
    }
);
define('../live2VOD/live2VOD.Util',['require','exports','module'],function (require, exports, module) {
    live2VOD.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            operate: function (cellvalue, options, rowObject) {
                return '<button type="button" onclick="live2VOD.Util.jumpToEdit(' + rowObject.id + ' )">修改</button>' + "|" + '<button onclick="live2VOD.Util.delChannel(' + rowObject.id + ')">删除</button>'
            },
            channeltypeShow: function (cellvalue, options, rowObject) {

                var rule = /[\u4E00-\u9FA5a-zA-Z0-9]+/g;
                var channeltype = rowObject.channeltype;

                var jsonArray = channeltype.match(rule);
                try {
                    var result = "";
                    $.each(jsonArray, function(i,data) {
                        result = result + data;
                        if (i < jsonArray.length - 1) {
                            result = result + "   ";
                        }
                    });
                    return result;
                } catch (e){return channeltype};
            },
            toUpperCase: function (cellvalue, options, rowObject) {
                return rowObject.ptype.toUpperCase();
            }
        },
        modifyChannel:function(params){
            live2VOD.Dao.modifyChannel(params, function (data) {
                //{"code": 200, "meta": {}, "response": {"msg": "success", "code": "A00000"}}
                if(data != null && data.code ==200 ){
                    if(data.response.code =="A00000" ){
                        EpgWeb.Plugin.showTips({content:"success" });
                        setTimeout(function(){
                            window.location.href = "/epg/live2VOD_cp_home.html"
                        } ,2000)
                    }else{
                        EpgWeb.Plugin.showTips({type:"error",content:data.response.msg })
                    }
                }else{
                    EpgWeb.Plugin.showTips({type:"error",content:"live2VOD modifyChannel has error" })
                }
            })
        },
        addChannel:function(params){
            live2VOD.Dao.addChannel(params, function (data) {
                //{"code": 200, "meta": {}, "response": {"msg": "success", "code": "A00000"}}
                if(data != null && data.code ==200 ){
                    if(data.response.code =="A00000" ){
                        EpgWeb.Plugin.showTips({content:"success" });
                        setTimeout(function(){
                            window.location.href = "/epg/live2VOD_cp_home.html"
                        } ,2000)
                    }else{
                        EpgWeb.Plugin.showTips({type:"error",content:data.response.msg })
                    }
                }else{
                    EpgWeb.Plugin.showTips({type:"error",content:"live2VOD addChannel has error" })
                }
            })
        },
        delChannel: function (id) {
            SystemDialog.queryConfirm("确认要删除么？",function(flag){
                if(flag){
                    if (id != null) {
                        var element = live2VOD.Util.getSelectElement(id);
                        var  $data = {channelalias:element.channelalias,channeltype:element.channeltype};
                        live2VOD.Dao.delChannel($data, function (data) {
                            //{"code": 200, "meta": {}, "response": {"msg": "success", "code": "A00000"}}
                            if(data != null && data.code == 200){
                                if(data.response.code =="A00000" ){
                                    EpgWeb.Plugin.showTips({content:"success" });
                                    $("button[name=channelQuery]").click();
                                }else{
                                    EpgWeb.Plugin.showTips({type:"error",content:data.response.msg })
                                }
                            }else{
                                EpgWeb.Plugin.showTips({type:"error",content:"live2VOD delChannel has error" })
                            }
                        })
                    }
                }
            })
        },
        getSelectElement: function (elementId) {
            var selectElement = null;
            var jsonData = live2VOD.Config.PageBean.getCur();
            $.each(jsonData.rows, function (i, element) {
                if (element.id == elementId) {
                    selectElement = element;
                    return false;
                }
            })
            return selectElement;
        },
        jumpToEdit: function (id) {
            var currentUrl = window.location.toString();
            var index = currentUrl.indexOf("live2VOD_cp_home.html");
            var openUrl = currentUrl.substr(0, index) + "live2VOD_edit.html";
            if (id != null) {
                var element = live2VOD.Util.getSelectElement(id);
                openUrl += "?channelalias=" + element.channelalias + "&channeltype=" + element.channeltype;
            }
            window.open(openUrl);
        },
        getValidator: function($container, config) {
            // var $container = this.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, config);

            return validator;
        }

    });
});
define(
    '../live2VOD/live2VOD.Edit',['require','exports','module'],function (require, exports, module) {
        live2VOD.Edit = function (options) {
            this.dao = live2VOD.Dao;
            this.config = live2VOD.Config;
            this.options = options || {};
        };
        Com.inherits(live2VOD.Edit, Ancestor.Grid).extend({
            init: function () {
                var self = this;
                self.initSuggest();
                self.fillForm();
                self.bindBasicEvent();
            },
            fillForm: function () {
                var channeltype = decodeURIComponent(live2VOD.Util.getUrlId("channeltype"));
                var channelalias = live2VOD.Util.getUrlId("channelalias");
                var self = this;
                if (channeltype != null && channelalias != null) {
                    self.dao.getList({channeltype: channeltype, channelalias: channelalias, pageNo: 0, pageSize: 1000 }, function (data) {
                        var retValue = null;
                        self.config.PageBean = live2VOD.Util.createPageBean();
                        if (data.code === 200 && data.response != null && data.response.data != null) {
                            self.config.PageBean.setNewData(data.response.data, self.config.TABLE_LIST.rowNum);
                        } else {
                            self.config.PageBean.setNewData([], self.config.TABLE_LIST.rowNum);
                        }
                        retValue = self.config.PageBean.getCur();
                        if (retValue.rows.length > 0) {
                            self.fillData(retValue.rows[0]);
                        } else {
                            self.fillNoData();
                        }
                    });
                } else {
                    self.fillNoData();
                }
                self.options.$form.find("input[name=ptype]").val("UGC");
                self.options.$form.find("input[name=ptype]").attr("disabled", "disabled");
            },
            fillData: function (element) {
                var self = this;
                //var selectDom = self.options.$form.find("select[name=channeltype]");
                //self.dao.getChannelType(function (data) {
                //    $.each(data, function (i, element) {
                //        $("<option>", {
                //            value: element.value,
                //            html: element.value
                //        }).appendTo(selectDom);
                //    });


                //});
                for (var key in element) {
                    if (key == "channeltype") {
                        var rule = /[\u4E00-\u9FA5a-zA-Z0-9]+/g;
                        var channeltype = element[key];
                        var jsonArray = channeltype.match(rule);
                        $.each(jsonArray, function (i, data) {
                            var tag_span = $('<span class="ui-suggest-value tagmanagerTag" data-tag-label="' + data + '">' + data + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');
                            $("#channeltype-val").append(tag_span);
                            if (i == 0) {
                                //self.options.$form.find("option[value=" + data + "]").attr('selected', true);
                                //$("option[value=" + data + "]").attr('selected', true);
                                //selectDom.val(data);
                            }
                        });
                    } else {
                        self.options.$form.find("input[name=" + key + "]").val(element[key]);
                    }
                }
                //self.options.$form.find("select[name=channeltype]").attr("disabled", "disabled");
                self.options.$form.find("input[name=ptype]").attr("disabled", "disabled");
                self.options.$form.find("input[name=channelalias]").attr("disabled", "disabled");
            },
            fillNoData: function () {
                var self = this;
                //self.dao.getChannelType(function (data) {
                //    var selectDom = self.options.$form.find("select[name=channeltype]");
                //    $.each(data, function (i, element) {
                //        $("<option>", {
                //            value: element.value,
                //            html: element.value
                //        }).appendTo(selectDom);
                //    })
                //});
            },
            getParam: function () {
                var self = this;
                var params = {};
                var $form = self.options.$form;
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });
                $.each($elements, function (i, element) {
                    if (element.type == "button") {
                        return true;
                    }
                    if (element.name == "channeltype") {
                        var channeltypeJson;
                        var channeltypes = $("#channeltype-val").find("span.ui-suggest-value");
                        if (channeltypes.length <= 0) {

                        } else {
                            for (i=0; i<channeltypes.length; i++) {
                                if (i == 0) {
                                    channeltypeJson = '[';
                                }
                                var channeltype = $(channeltypes[i]).attr("data-tag-label");
                                channeltypeJson = channeltypeJson + '"' + channeltype + '"';
                                if (i == channeltypes.length-1) {
                                    channeltypeJson = channeltypeJson + ']';
                                } else {
                                    channeltypeJson = channeltypeJson + ',';
                                }
                            }
                        }
                        params["channeltype"] = channeltypeJson;
                        return true;
                    }
                    params[element.name] = $(element).val();
                })
                    if (self.config.PageBean != null) {
                    var dataArr = self.config.PageBean.getCur().rows;
                    if (dataArr.length > 0) {
                        params["srcchannelalias"] = dataArr[0].channelalias;
                        params["srcchanneltype"] = dataArr[0].channeltype;
                    }
                }
                return params;
            },
            bindBasicEvent: function () {
                var self = this;
                $("button[name=commitBtn]").bind("click", function (event) {
                    if (! self.$validator.form()){
                        console.log("验证失败");
                        return;
                    }
                    var params = self.getParam()
                    if (params["channeltype"] == null) {
                        SystemDialog.queryAlert("频道类型为空，提交失败!");
                        return;
                    }
                    if (self.config.PageBean != null) {
                        live2VOD.Util.modifyChannel(self.getParam())
                    } else {
                        live2VOD.Util.addChannel(self.getParam())
                    }
                })
                $.validator.addMethod("selfReg",function(value,element,params){
                    return params.test(value);
                },"需要大写字母或阿拉伯数字")
                self.$validator =  live2VOD.Util.getValidator(self.options.$form, self.config.EDIT_VALIDATOR);

                $("#channeltype").on('change', function() {
                    var val = $(this).find("option:selected").text();
                    var channeltypes = $("#channeltype-val").find("span");
                    var flag = true;
                    for (i=0; i<channeltypes.length; i++) {
                        var channeltype = $(channeltypes[i]).attr("data-tag-label");
                        if (val == channeltype) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        var tag_span = $('<span class="ui-suggest-value tagmanagerTag" data-tag-label="' + val + '">' + val + '<a class="tagmanagerRemoveTag"  onclick="$(this).parent().remove();"  title="Remove" href="javascript:;">x</a></span>');
                        $("#channeltype-val").append(tag_span);
                    }
                });
            },
            initSuggest: function () {
                var self = this;
                var channelTypeSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        renderPanel: function (handler) {
                            self.dao.getChannelType(handler)
                        },
                        method: "post",
                        multiple: true,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {size: 100} : {word: term, size: 100}
                            var requestData = {url: live2VOD.Constant.thirdUrl_channel_type, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                $("input[name=channeltype]").suggest(channelTypeSuggest.options);
                $("input[name=channeltype]").suggest("setSelectedItem", null);
            }
        })
    }
);
define(
    '../live2VOD/live2VOD.Grid',['require','exports','module'],function (require, exports, module) {
        live2VOD.Grid = function (options) {
            this.dao = live2VOD.Dao;
            this.config = live2VOD.Config;
            this.options = options || {};
        };
        Com.inherits(live2VOD.Grid, Ancestor.Grid).extend({
            runList: function (options, callback) {
                var self = this;
                self.$grid = $('#list');
                self.initSuggest();
                self.bindBasicEvent();
                self.initListGrid();
                self.config.PageBean = live2VOD.Util.createPageBean();
                self.query();
            },
            bindBasicEvent: function () {
                var self = this;
                $("button[name=createBtn]").bind("click", function (event) {
                    live2VOD.Util.jumpToEdit();
                })
                $("button[name=channelQuery]").bind("click", function (event) {
                    self.query();
                })
            },
            initListGrid: function (options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                options = $.extend(true, {}, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            query: function () {
                var self = this;
                self.dao.getList(self.getParam(), function (data) {
                    var retValue = null;
                    if (data.code === 200 && data.response != null && data.response.data != null) {
                        $.each(data.response.data, function (i, element) {
                            element.channeltypeShow = live2VOD.Util.formatter.channeltypeShow(null, null, element);
                            element.id = i;
                        })
                        self.config.PageBean.setNewData(data.response.data, self.config.TABLE_LIST.rowNum);
                    } else {
                        self.config.PageBean.setNewData([], self.config.TABLE_LIST.rowNum);
                    }
                    retValue = self.config.PageBean.getCur();
                    self.$grid[0].addJSONData(retValue)
                });
            },
            getParam: function () {
                var self = this;
                var params = {};
                var $form = $('form[name="basicFrm"]')
                var selectedElement = $("input[name=channeltype]").suggest("getSelectedItem")
                if (selectedElement == null) {
                    console.log("channeltype is empty")
                } else if (selectedElement.value != $("input[name=channeltype]").val()) {
                    console.log("value ne", selectedElement.value, $("input[name=channeltype]").val())
                } else {
                    params.channeltype = selectedElement.value;
                }
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });
                var filterNameArr = ["channeltype"];
                $.each($elements, function (i, element) {
                    if (element.type == "text") {
                        if (filterNameArr.indexOf(element.name) == -1) {
                            params[element.name] = $.trim($(element).val()) || '';
                        }
                    }
                });
                params.pageNo = 0;
                params.pageSize = 1000;
                return params;
            },
            initSuggest: function () {
                var self = this;
                var channelTypeSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        renderPanel: function (handler) {
                            self.dao.getChannelType(handler)
                        },
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {size: 100} : {word: term, size: 100}
                            var requestData = {url: live2VOD.Constant.thirdUrl_channel_type, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }
                $("input[name=channeltype]").suggest(channelTypeSuggest.options);
                $("input[name=channeltype]").suggest("setSelectedItem", null);
            }
        })
    }
);
define(
    '../broadcast/Broadcast',['require','exports','module'],function(require, exports, module) {
        window.Broadcast = window.Broadcast || {
            version: '1.0'
        };
    }
);
define(
    '../broadcast/Broadcast.Action',['require','exports','module'],function (require, exports, module) {
        Broadcast.Action = (function () {
            var configGrid = null;
            var broadcastChannel = null;
            var broadcastEpisode = null;

            function configRun(){
                if (!configGrid) {
                    configGrid = new Broadcast.Grid($.extend(true, {
                        type: 0
                    }, {}));
                }
                configGrid.runConfig();
                console.log('config grid run');
            }

            function broadcastChannelRun(){
                if (!broadcastChannel) {
                    broadcastChannel = new Broadcast.Edit($.extend(true, {
                        model:"channel",
                        type: 0
                    }, {}));
                }
                broadcastChannel.channelRun();
                console.log('broadcastChannel run');
            }
            function broadcastEpisodeRun(){
                if (!broadcastEpisode) {
                    broadcastEpisode = new Broadcast.Edit($.extend(true, {
                        model:"episode",
                        type: 0
                    }, {}));
                }
                broadcastEpisode.episodeRun();
                console.log('broadcastEpisode run');
            }

            return {
                configRun:configRun,
                broadcastChannelRun:broadcastChannelRun,
                broadcastEpisodeRun:broadcastEpisodeRun
            }
        })();
    }
);

///import js-src/lib/
///import js-src/com/
define('../broadcast/Broadcast.Config',['require','exports','module'],function (require, exports, module) {
    Broadcast.Config = $.extend({}, Ancestor.Config, {
        TABLE_COLMODEL_CONFIG:{
            configId:{
                name: "id",
                index: 'id',
                title: false,
                hidden: true,
                sortable: false
            },
            descr:{
                name: "descr",
                index: 'key',
                title: false,
                sortable: false
            },
            online:{
                index: 'online',
                sortable: false,
                formatter: function (v, o, r) {
                    return Broadcast.Util.formatter.online(v, o, r);
                }
            },
            region:{
                index: 'region',
                sortable: false,
                formatter:function (v, o, r) {
                    return Broadcast.Util.formatter.region(v, o, r);
                }
            }
        },
        TABLE_CONFIG:{
            multiselect: false,
            datatype: "local",
            localReader: {
                id: "key",
                root: "rows",
                page: "page",
                total: "total",
                records: "records"
            },
            colModel:["configId","descr","online","region"],
            colNames:["平台编号", "平台", "启用上下线限制", "启用地域限制"]
        },

         ERROR_MSG:{
             bossAlertMsg: "勾选后付费节目",
             copyrightAlertMsg: "勾选后无版权节目",
             publishAlertMsg: "勾选后未发布节目",
             clientAlertMsg1: "未上线的节目",
             clientAlertMsg2: "有地域播控的节目"
         },
        Mode:null
    })



});
define(
    '../broadcast/Broadcast.Dao',['require','exports','module'],function (require, exports, module) {
        Broadcast.Dao = $.extend({}, EpgWeb.Dao, {
            channelId: 0,
            programId: 0,
            cfgName: {
                platSettings: "platSettings",
                PlayPlatform: "PlayPlatform",
                entityName: "entityName",
                broadcastControl: "broadcastControl",
                reservation: "reservation",
                saveData: "saveData",
                getChannel: "getChannel",
                platforms: "platforms",
                programbroadcastControl: "programbroadcastControl"
            },
            //==============================================/
            createEntity: function () {
                var self = this;
                return {
                    id: self.channelId,
                    checkBossType: -1,
                    checkPublishType: -1,
                    checkCopyRightType: -1,
                    regionLimitArr: [],
                    onlineLimitArr: []
                }
            },
            createControlData: function () {
                var entity = {};
                entity.platform = 0;
                entity.availableStatus = false;
                entity.liveDelayTime = 0;
                entity.blacklist = "";
                entity.rejectSearch = false;
                entity.regionRejectSearch = false
                return entity;
            },
            copyControlData: function (oldData) {
                var self = this;
                var entity = self.createControlData();
                entity.platform = oldData.platform;
                entity.availableStatus = oldData.availableStatus;
                entity.liveDelayTime = oldData.liveDelayTime;
                entity.blacklist = oldData.blacklist;
                entity.rejectSearch = oldData.rejectSearch;
                entity.regionRejectSearch = oldData.regionRejectSearch;
                return entity;
            },
            //==============================================/
            getPlatSettings: function () {
                return this.getDataByName(this.cfgName.platSettings)
            },
            getPlatforms: function () {
                return this.getDataByName(this.cfgName.PlayPlatform)
            },
            getChannel: function () {
                return this.getDataByName(this.cfgName.getChannel).data
            },
            getBroadcastControls: function () {
                return this.getDataByName(this.cfgName.broadcastControl);
            },
            getProgramBroadcastControls: function () {
                return this.getDataByName(this.cfgName.programbroadcastControl);
            },
            //==============================================/
            savePlatSettings: function (data, callback) {
                var submitEntity = data;
                var options = {
                    url: EpgWeb.urlConfig.platSettingsSaveUrl,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function (data) {
                        callback.call(this, data, submitEntity);
                    },
                    error: function (data) {
                        callback.call(this, data, submitEntity);
                    }
                };
                Ancestor.Dao.ajax(options, '/channel/savePlatSettings');
            },

            saveData: function (copyToAll, data, callback) {
                var sendUrl = copyToAll ? EpgWeb.urlConfig.setBroadcastControlAllUrl : EpgWeb.urlConfig.setBroadcastControl;
                var options = {
                    url: sendUrl,
                    type: "post",
                    data: data,
                    dataType: "json",
                    success: function (data) {
                        callback(data);
                    },
                    error: function (data) {
                        callback(null);
                    }
                }
                Ancestor.Dao.ajax(options, sendUrl.replace("/api", ""));
            },
            saveEpisodeData: function (copyToAll, data, callback) {
                var sendUrl = EpgWeb.urlConfig.programBroadcastControlUrl;
                var options = {
                    url: sendUrl,
                    type: "post",
                    data: data,
                    dataType: "json",
                    success: function (data) {
                        callback(data);
                    },
                    error: function (data) {
                        callback(null);
                    }
                }
                Ancestor.Dao.ajax(options, sendUrl.replace("/api", ""));
            }
        })
    }
);
define('../broadcast/Broadcast.Util',['require','exports','module'],function (require, exports, module) {
    Broadcast.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            online: function (cellvalue, options, rowObject) {
                var onlineKey = "onlineKey_" + rowObject.key;
                return "<label class='radio inline'><input type='radio' value='1' name='" + onlineKey + "' >启用</label><label class='radio inline'><input type='radio'  value='-1' name='" + onlineKey + "'>不启用</label>"
            },
            region: function (cellvalue, options, rowObject) {
                var regionKey = "regionKey_" + rowObject.key;
                return "<label class='radio inline'><input type='radio' value='1' name='" + regionKey + "' >启用</label><label class='radio inline'><input type='radio'  value='-1' name='" + regionKey + "'>不启用</label>"
            }
        },
        makeBlackList: function (regName) {
            var htmlArr = [];
            var channel = Broadcast.Dao.getChannel();
            if (channel['liveType'] == 3) {
                htmlArr.push('<div style="height:100%;width:100%;position:absolute;background: rgba(0, 0, 0, 0.1);z-index:1;"></div>');
            }
            htmlArr.push('<div  class="control-group"> <span style="background-color:#ff8c00 ;color: #ffffff;padding-right: 15px;padding-left: 10px;border-bottom-right-radius: 8px" >地域黑名单</span></div>')
            htmlArr.push('<div class="control-group">');
            htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_95_香港,3_148_澳门,3_228_台湾,6_301_海外">海外地区限制：香港、澳门、台湾、海外</label>');
            //   htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_2_上海,3_1_北京,4_3001_广东省广州市,4_3003_广东省深圳市">一线城市限制：上海、北京、广州、深圳</label>');
            htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_2_上海,3_1_北京,4_3001_广州,4_3003_深圳">一线城市限制：上海、北京、广州、深圳</label>');
            htmlArr.push('<label class="checkbox inline"><input type="checkbox" name="area_select" value="3_1_北京,3_4_天津">京津地区限制：北京、天津</label>');
            htmlArr.push('</div>');
            htmlArr.push('<div  class="control-group"><span>自定义地域限制</span>');
            htmlArr.push('<input type="text" class="inline" name="localSuggest" placeholder="输入地区关键字检索" autocomplete="off">')
            htmlArr.push('</div>');
            htmlArr.push('<div  class="control-group"><span>地域展现控制：</span><label class="checkbox inline"><input type="checkbox" name="regionRejectSearch" value="0" >屏蔽搜索</label></div>');
            return '<div style="border-style: dashed ;border-width: 1px;position: relative;">' + htmlArr.join("") + "</div>";
        },

        makePlatformZone: function (index) {
            var self = this;
            var htmlArr = [];
            var regName = "platform_" + index;
            htmlArr.push(self.onlineZone(regName));
            htmlArr.push(self.searchZone(regName));
            htmlArr.push(self.broadcastDelayZone(regName));
            if(Broadcast.Config.Mode == "channel"){
                htmlArr.push(self.broadcastApplyZone(regName));
            }
            htmlArr.push(self.makeBlackList(regName));
            return htmlArr.join("");
        },

        onlineZone: function (radioName) {
            var htmlArr = [];
            htmlArr.push('<div class="control-group">');
            htmlArr.push('<span>上下线状态：</span>');
            htmlArr.push('<input type="radio" name="' + radioName + '" value="1"><span>上线</span>');
            htmlArr.push('<input type="radio" name="' + radioName + '" value="0"><span>下线</span>');
            htmlArr.push('</div>');
            return htmlArr.join("");
        },

        searchZone: function (regName) {
            var htmlArr = [];
            htmlArr.push('<div class="control-group">');
            htmlArr.push('<span>展现控制：</span><label class="checkbox inline"><input type="checkbox" name="rejectSearch" value="0" >屏蔽搜索</label>');
            htmlArr.push('</div>');
            return htmlArr.join("");
        },

        broadcastDelayZone: function (regName) {
            var htmlArr = [];
            htmlArr.push('<div class="control-group" style="display:none">');
            htmlArr.push('<span>PC网页端延时：</span><input  name="' + regName + '_delay" type="text"> 秒');
            htmlArr.push('</div>');
            return htmlArr.join("");
        },
        broadcastApplyZone: function (regName) {
            var htmlArr = [];
            htmlArr.push('<div class="control-group">');
            htmlArr.push('<label class="col-xs-2 control-label" style="width: 170px">频道播控是否立即对节目生效：<span class="form-must">*</span></label><label class="radio inline"><input type="radio" name="app_on_episode" value="true" >是</label><label class="radio inline"><input type="radio" name="app_on_episode" value="false" >否' +
                '</label>');
            htmlArr.push('</div>');
            var lastDate = new Date();
            lastDate.setHours(0);
            lastDate.setMinutes(0);
            lastDate.setSeconds(0);
            lastDate.setMilliseconds(0);
            lastDate.setTime(lastDate.getTime()+86400000*2);
            htmlArr.push('<div class="control-group" ><span style="color: red">注： 未开始2天内节目的播控才能被频道播控覆盖！</span>即从现在到'+Broadcast.Util.quickDateFormat(lastDate)+'之前的节目的播控可以被覆盖。</div>');

            return htmlArr.join("");
        },
        makeTabPanel: function (obj) {
            var divIndex = obj.key;
            var htmlArr = [];
            var tabPanelName = "tabPanel_" + divIndex;
            htmlArr.push('<div id="' + tabPanelName + '">');
            htmlArr.push('<div class="container">');
            htmlArr.push('<div name="locationControl" >' + Broadcast.Util.makePlatformZone(divIndex) + '</div>');
            htmlArr.push('</div>');
            htmlArr.push('</div>');
            return htmlArr.join("");
        },
        fixLocaltion: function (originValue) {
            var regFixLocaltion = /^\W*省|市$/g;
            if (originValue == null) {
                return "";
            }
            return originValue.replace(regFixLocaltion, "");
        },
        formatToLocationItem: function (inputStr) {
            var self = this;
            var ret = [];
            var items = inputStr.split(",")
            $.each(
                items, function (i, item) {
                    item = item.split('_');
                    var itemData = {};
                    itemData["label"] = self.fixLocaltion(item[2]);
                    itemData["id"] = item[0] + "_" + item[1];
                    ret.push(itemData);
                }
            );
            return ret;
        },


        formatCompareString: function (obj) {
            return obj.availableStatus + "|" + obj.blacklist + "|" + obj.liveDelayTime + "|" + obj.rejectSearch + "|" + obj.regionRejectSearch;
        }

    });


});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../broadcast/Broadcast.Task',['require','exports','module'],function (require, exports, module) {
        Broadcast.Task = $.extend({}, EpgWeb.Task, {
            getPlayPlatform: function (taskName, callback) {
                var self = this;
                return self.getConfigType(taskName, callback)
            },
            getPlatSettings: function (regName, channelId) {
                return {
                    regName: regName,
                    options: {
                        url: EpgWeb.urlConfig.platSettingsGetUrl,
                        type: "post",
                        data: {channelId: channelId},
                        dataType: "json"
                    }
                }
            },
            getChannel: function (regName, channelId) {
                return {
                    regName: regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: {id: channelId}
                    }
                }
            },
            getBroadcastTask: function (regName, channelId) {
                return {
                    regName: regName,
                    options: {
                        url: EpgWeb.urlConfig.getBroadcastControls,
                        type: "get",
                        dataType: "json",
                        data: {channelId: channelId}
                    }
                }
            },
            getProgramBroadcastTask: function (regName, programId) {
                return {
                    regName: regName,
                    options: {
                        url: EpgWeb.urlConfig.programBroadcastControlUrl,
                        type: "get",
                        dataType: "json",
                        data: {programId: programId}
                    }
                }
            }
        })
    }
);
define(
    '../broadcast/Broadcast.Edit',['require','exports','module'],function (require, exports, module) {
        Broadcast.Edit = function (options) {
            this.dao = Broadcast.Dao;
            this.task = Broadcast.Task;
            this.config = Broadcast.Config;
            this.options = options || {};
        };
        Com.inherits(Broadcast.Edit, Ancestor.Grid).extend({
            channelRun: function () {
                $("#buttonDiv").hide();
                $("#hintPart").hide();
                var channelId = Com.url.getParameter("id");
                if (channelId == null || isNaN(channelId)) {
                    EpgWeb.Plugin.showTips({content: "need channelId", type: "error"})
                    return;
                }
                var self = this;
                self.initDialog();
                Broadcast.Config.Mode = self.options.model;
                self.dao.channelId = parseInt(channelId);
                var taskArr = [];
                taskArr.push(self.task.getPlayPlatform(self.dao.cfgName.PlayPlatform, function (data) {
                    self.fillNavBar(data);
                }));
                taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, self.dao.channelId));
                taskArr.push(self.task.getBroadcastTask(self.dao.cfgName.broadcastControl, self.dao.channelId));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })

                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.initTypeChannel();
                });
                EpgWeb.ajaxQueue.startLoad();
            },

            initTypeChannel: function () {
                console.log("init end");
                var self = this;
                self.initPanelContainer();
                self.bindClickHandler();
                self.fillInitTabPanelDefault();
                self.fillInitTabPanel();
                self.initBlacklistDefault();
                self.initSuggestChannel();

                //self.initLocationAreaMask();

            },
            fillNavBar: function (data) {
                if (data != null) {
                    console.log(data.code);
                }
                if (data != null && data.code == "A00000") {
                    var navDiv = $("#navDiv");
                    var ulPart = $("<ul></ul>");
                    var createDate = data.data;
                    $("<li hidden><a href='#tabPanel_0'>0</a></li>").appendTo(ulPart);
                    $.each(createDate, function (index, obj) {
                        $("<li><a href='#tabPanel_" + obj.key + "'>" + obj.descr + "</a></li>").appendTo(ulPart);
                    })
                    ulPart.prependTo(navDiv);
                    navDiv.find("ul").hide();
                }
            },
            bindClickHandler: function () {
                var self = this;
                $("input[name=clientSetting]").click(function (event) {
                    if (event.currentTarget.value == 0) {
                        $("#navDiv").tabs({active: 0});
                        $("#navDiv").find("ul").hide();
                    } else {
                        $("#navDiv").tabs({active: 1});
                        $("#navDiv").find("ul").show();
                    }
                })
                $("input[name=submitBtn]").click(function (event) {
                    if(self.submitFun()){
                        $("input[name=submitBtn]").attr("disabled", "disabled")
                    }
                    // Broadcast.Dao.submitFun(false)
                });
                $("input[name=area_select]").click(function (event) {
                    var jObj = $(event.currentTarget.parentNode.parentNode);
                    var child = $(event.currentTarget);
                    var selectArr = Broadcast.Util.formatToLocationItem(child.val());
                    var suggestInput = jObj.parent().find("input[name=localSuggest]");
                    if (child.prop("checked") == true) {
                        for (var i = 0; i < selectArr.length; i++) {
                            suggestInput.suggest("addValue", selectArr[i]);
                        }
                    } else {
                        for (var i = 0; i < selectArr.length; i++) {
                            var el = suggestInput.parent().find("span[data-tag-id=" + selectArr[i].id + "]").find("a");
                            if (el.length > 0) {
                                suggestInput.suggest("removeValue", el);
                            }
                        }
                    }
                })
            },
            submitFun: function () {
                var self = this;
                var copyToAll = $("input[name=clientSetting]:checked").val() == 0
                if (self.options.model == "channel") {
                    var $showTabPanel = $("div[aria-hidden=false]");
                    var assignToPrograms = $showTabPanel.find("input[name=app_on_episode]:checked").val();
                    if (null == assignToPrograms) {
                        EpgWeb.Plugin.showTips({content: "频道播控是否立即对节目生效 必填", type: "error"})
                        return false;
                    }
                    self.doSaveData(copyToAll);
                } else if (self.options.model == "episode") {
                    self.doSaveEpisodeData(copyToAll);
                }
                return true;
            },
            doSaveData: function (copyToAll) {
                var self = this;
                var $showTabPanel = $("div[aria-hidden=false]")
                var locationControl = $showTabPanel.find("div[name=locationControl]");
                var onlineValue = locationControl.find("input[type=radio]:checked").val();
                var rejectSearchValue = locationControl.find("input[name=rejectSearch]").prop("checked") == true;
                var regionRejectSearchValue = locationControl.find("input[name=regionRejectSearch]").prop("checked") == true;
                var delayValue = locationControl.find("input[name$=delay]").val()
                var locationResult = locationControl.find(".tagmanagerTag")
                var saveBlackList = [];
                $.each(locationResult, function (index, obj) {
                    saveBlackList.push(obj.getAttribute("data-tag-id") + "_" + obj.getAttribute("data-tag-label"))
                })

                var sendData = {channelId: self.dao.channelId, params: null, assignToPrograms: "" };
                var assignToPrograms = $("input[name=app_on_episode]:checked").val();
                sendData.assignToPrograms = assignToPrograms || "";

                var platformKey = parseInt($showTabPanel.attr("id").split("_")[1]);
                var entityData = self.dao.createControlData();
                entityData.platform = platformKey;
                entityData.blacklist = saveBlackList.join(",");
                entityData.rejectSearch = rejectSearchValue;
                if ($.trim(delayValue).length == 0 || isNaN(delayValue)) {
                    entityData.liveDelayTime = 0;
                } else {
                    entityData.liveDelayTime = parseInt($.trim(delayValue));
                }
                entityData.availableStatus = parseInt(onlineValue) == 1 ? true : false;
                entityData.regionRejectSearch = regionRejectSearchValue
                var dataArr = [];
                if (copyToAll) {
                    var responseData = self.dao.getPlatforms();
                    var createDate = responseData.data;
                    var platformArr = [];
                    $.each(createDate, function (index, obj) {
                        platformArr.push(obj.key)
                    })
                    sendData.platforms = JSON.stringify(platformArr);
                    sendData.params = JSON.stringify(entityData);
                } else {
                    dataArr.push(entityData);
                    sendData.params = JSON.stringify(dataArr);
                }
                console.log("sendData:" + JSON.stringify(sendData));
                self.dao.saveData(copyToAll, sendData, function (data) {
                    self.submitCallHandler(data,copyToAll);
                })
            },

            doSaveEpisodeData: function (copyToAll) {
                var self = this;
                var $showTabPanel = $("div[aria-hidden=false]")
                var locationControl = $showTabPanel.find("div[name=locationControl]");
                var onlineValue = locationControl.find("input[type=radio]:checked").val();
                var rejectSearchValue = locationControl.find("input[name=rejectSearch]").prop("checked") == true;
                var regionRejectSearchValue = locationControl.find("input[name=regionRejectSearch]").prop("checked") == true;
                var delayValue = locationControl.find("input[name$=delay]").val()
                var locationResult = locationControl.find(".tagmanagerTag")
                var saveBlackList = [];
                $.each(locationResult, function (index, obj) {
                    saveBlackList.push(obj.getAttribute("data-tag-id") + "_" + obj.getAttribute("data-tag-label"))
                })
                var sendData = {programId: self.dao.programId, params: null, channelId: self.dao.channelId }
                var platformKey = parseInt($showTabPanel.attr("id").split("_")[1]);
                var entityData = self.dao.createControlData();
                entityData.platform = platformKey;
                entityData.blacklist = saveBlackList.join(",");
                entityData.rejectSearch = rejectSearchValue;
                entityData.liveDelayTime = 0;
                entityData.availableStatus = parseInt(onlineValue) == 1 ? true : false;
                entityData.regionRejectSearch = regionRejectSearchValue
                var dataArr = [];
                if (copyToAll) {
                    var responseData = self.dao.getPlatforms();
                    var createDate = responseData.data;
                    var platformArr = [];
                    $.each(createDate, function (index, obj) {
                        platformArr.push(obj.key)
                    })
                    sendData.platforms = JSON.stringify(platformArr);
                    sendData.params = JSON.stringify(entityData);
                } else {
                    dataArr.push(entityData);
                    sendData.params = JSON.stringify(dataArr);
                }

                if (copyToAll) {
                    var responseData = self.dao.getPlatforms();
                    var createDate = responseData.data;
                    var platformArr = [];
                    $.each(createDate, function (index, obj) {
                        platformArr.push(obj.key)
                    })
                    sendData.platforms = JSON.stringify(platformArr);
                    sendData.params = JSON.stringify(entityData);
                } else {
                    sendData.params = JSON.stringify(entityData);
                }
                console.log("sendData:" + JSON.stringify(sendData));
                self.dao.saveEpisodeData(copyToAll, sendData, function (data) {
                    self.submitCallHandler(data,copyToAll);
                })
            },
            submitCallHandler: function (data,copyToAll) {
                if (data != null) {
                    console.log("data" + data.msg);
                    if (data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: data.msg })
                        if (copyToAll) {
                            $("#refreshMessage").dialog("open")
                            setTimeout(function () {
                                location.reload()
                            }, 1500)
                        }
                    } else {
                        EpgWeb.Plugin.showTips({content: data.msg, type: "error" })
                    }
                } else {
                    EpgWeb.Plugin.showTips({content: "提交数据发生异常", type: "error"})
                }
                $("input[name=submitBtn]").removeAttr("disabled", "disabled")
            },
            fillInitTabPanelDefault: function () {
                var tabPanelArr = $("div[id^=tabPanel_]");
                $.each(tabPanelArr, function (index, obj) {
                    tabPanelArr.find("input[type=radio][value=0]").prop("checked", true);
                    tabPanelArr.find("input[name$=delay]").val(0);
                })
            },
            fillInitTabPanel: function () {
                var self = this;
                var responseData = null;
                if (self.options.model == "channel") {
                    responseData = self.dao.getBroadcastControls();
                    if (responseData.data.length == 0) {
                        return;
                    }
                } else if (self.options.model == "episode") {
                    responseData = self.dao.getProgramBroadcastControls();
                    if (responseData.data.length == 0) {
                        responseData = self.dao.getBroadcastControls();
                        return;
                    }
                }
                responseData.data.sort(function (a, b) {
                    return a.platform > b.platform ? 1 : -1;
                })
                var totalLength =  Broadcast.Dao.getPlatforms().data.length;
                var isSame = responseData.data.length > 1;
                var fetchTarget = null;
                $.each(responseData.data, function (index, obj) {
                    obj.unicodeSign = Broadcast.Util.formatCompareString(obj);
                    if (fetchTarget == null) {
                        fetchTarget = obj;
                    } else if (isSame) {
                        isSame = fetchTarget.unicodeSign == obj.unicodeSign;
                        if (!isSame) {
                            fetchTarget = obj;
                        }
                    }
                    self.fillPanelData(obj)
                });
                isSame = isSame && responseData.data.length == totalLength;
                if (isSame) {
                    self.fillPanelData(fetchTarget, 0)
                } else {
                    $("input[name=clientSetting][value=" + 1 + "]").click();
                    $("#navDiv").tabs({active: fetchTarget.platform});
                }
            },
            fillPanelData: function (obj, index) {
                if (index == null) {
                    index = obj.platform
                }
                var newTarget = $("#tabPanel_" + index);
                var onlineValue = obj.availableStatus ? 1 : 0;
                newTarget.find("input[type=radio][value=" + onlineValue + "]").prop("checked", true);

                if (obj.blacklist.length > 0) {
                    newTarget.find("input[name=localSuggest]").val(obj.blacklist);
                }
                //else{
                //    var channel = Broadcast.Dao.getChannel();
                //    var blacklist = '';
                //    if(channel['type'] == 5) {
                //        blacklist = '3_228_台湾';
                //        newTarget.find("input[name=localSuggest]").val(blacklist);
                //    }else if(channel['type'] == 11) {
                //        blacklist = '3_2_上海,3_1_北京,4_3001_广州,4_3003_深圳,3_4_天津,3_31_西藏,3_30_甘肃,3_26_云南,3_6_山东,3_3_广东,3_22_新疆,3_7_河北,3_10_浙江,3_19_江苏,3_29_青海,3_12_安徽,3_18_贵州,3_16_福建,3_11_湖北,3_28_宁夏,3_15_内蒙古,3_25_海南,3_17_辽宁,3_21_吉林,3_24_黑龙江,3_8_山西,3_13_陕西,3_20_四川,3_5_重庆,3_14_江西,3_27_湖南,6_301_海外,3_148_澳门,3_95_香港';
                //        newTarget.find("input[name=localSuggest]").val(blacklist);
                //    }
                //}
                newTarget.find("input[name$=delay]").val(obj.liveDelayTime);
                if (obj.rejectSearch == true) {
                    newTarget.find("input[name=rejectSearch]").prop("checked", true)
                }
                if (obj.regionRejectSearch == true) {
                    newTarget.find("input[name=regionRejectSearch]").prop("checked", true)
                }
            },
            initSuggestChannel: function () {
                var self = this;
                var options = {
                    source: EpgWeb.urlConfig.redirect,
                    parseValue: function () {
                        var self = this;
                        var val = this.element.val(),
                            ret = [],
                            items = null,
                            itemData = null,
                            options = self.options;

                        if (val) {
                            items = val.split(',');
                            $.each(
                                items, function (i, item) {
                                    item = item.split('_');
                                    itemData = {};
                                    itemData[options.labelKey] = Broadcast.Util.fixLocaltion(item[2]);
                                    itemData[options.valueKey] = item[0] + "_" + item[1];
                                    ret.push(itemData);
                                }
                            );
                        }
                        this._value('');
                        return ret;
                    },
                    process: function (json) {
                        var ret = [],
                            self = this,
                            options = self.options,
                            itemData = null;
                        var data = null;
                        if (json.code === "A00000") {
                            data = $.isArray(json) ? json : json.data;
                        }
                        if (!data) {
                            return [];
                        }
                        $.map(data, function (item) {
                            itemData = {};
                            itemData[options.valueKey] = item["type"] + "_" + item["code"];
                            itemData[options.labelKey] = item["originalName"];
                            ret.push(itemData);
                        });
                        return ret;
                    },
                    method: "post",
                    getParam: function (owner, term) {
                        var requestData = {url: EpgWeb.Constant.third_location_url, type: "get", params: {word: this.element.val()}};
                        return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    },
                    template: function (item) {
                        return '<div class="contract-item" >' + item.label + '</div>';
                    }
                }
                $("input[name=localSuggest]").suggest(options);

                //self.initBlacklistDefault();
            },

            initBlacklistDefault: function() {
                var channel = Broadcast.Dao.getChannel();
                var controls = $('input[name=localSuggest]');
                var blacklist = '';
                if(channel['type'] == 5) {
                    blacklist = '3_228_台湾';
                } else if(channel['type'] == 11) {
                    blacklist = '3_2_上海,3_1_北京,4_3001_广州,4_3003_深圳,3_4_天津,3_31_西藏,3_30_甘肃,3_26_云南,3_6_山东,3_3_广东,3_22_新疆,3_7_河北,3_10_浙江,3_19_江苏,3_29_青海,3_12_安徽,3_18_贵州,3_16_福建,3_11_湖北,3_28_宁夏,3_15_内蒙古,3_25_海南,3_17_辽宁,3_21_吉林,3_24_黑龙江,3_8_山西,3_13_陕西,3_20_四川,3_5_重庆,3_14_江西,3_27_湖南,6_301_海外,3_148_澳门,3_95_香港';
                }
                if(blacklist != '') {
                    $.each(controls, function(index, e) {
                        $(e).val(blacklist);
                    })
                }
            },
            initDialog: function () {
                var self = this;
                $("#refreshMessage").dialog({
                    title: "等待页面刷新",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                });
                $("#saveMessage").dialog({
                    title: "同步数据保存",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    buttons: {
                        "确定": function () {
                            self.submitFun();
                            $(this).dialog("close");
                        },
                        "取消": function () {
                            $(this).dialog("close");
                        }
                    }
                });
            },

//==================initTypeChannel end=============//

//==================com method end=============//
            initPanelContainer: function () {
                var self = this;
                var channelEntity = self.dao.getChannel();
                if (channelEntity.liveType == 2) {
                    $("#hintPart").show();
                }
                var htmlArr = [];
                var responseData = self.dao.getPlatforms();
                var createDate = responseData.data;
                htmlArr.push(Broadcast.Util.makeTabPanel({key: 0}));
                $.each(createDate, function (index, obj) {
                    htmlArr.push(Broadcast.Util.makeTabPanel(obj))
                });

                $("input[name=clientSetting]").removeAttr("checked");
                $("input[name=clientSetting]" + "[value=0]").prop("checked", true);
                $("<div id='tabsDiv'></div>").html(htmlArr.join("")).appendTo($("#navDiv"));
                $("#navDiv").tabs({active: 0});
                $("#buttonDiv").show();
            },

//==================initTypeChannel end=============//
            episodeRun: function () {
                $("#buttonDiv").hide();
                $("#hintPart").hide();
                var channelId = Com.url.getParameter("id");
                if (channelId == null || isNaN(channelId)) {
                    EpgWeb.Plugin.showTips({content: "need channelId", type: "error"})
                    return;
                }
                var programId = Com.url.getParameter("programId");
                if (programId == null || isNaN(programId)) {
                    EpgWeb.Plugin.showTips({content: "need programId", type: "error"})
                    return;
                }
                var self = this;
                self.initDialog();
                self.dao.channelId = parseInt(channelId);
                self.dao.programId = parseInt(programId);
                Broadcast.Config.Mode = self.options.model;
                var taskArr = [];
                taskArr.push(self.task.getPlayPlatform(self.dao.cfgName.PlayPlatform, function (data) {
                    self.fillNavBar(data);
                }));
                taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, self.dao.channelId));
                taskArr.push(self.task.getBroadcastTask(self.dao.cfgName.broadcastControl, self.dao.channelId));
                taskArr.push(self.task.getProgramBroadcastTask(self.dao.cfgName.programbroadcastControl, self.dao.programId));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })

                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.initTypeEpisode();
                });
                EpgWeb.ajaxQueue.startLoad();
            },
            initTypeEpisode: function () {
                console.log("init end");
                var self = this;
                self.initPanelContainer();
                self.bindClickHandler();
                self.fillInitTabPanelDefault();
                self.fillInitTabPanel();
                self.initSuggestChannel();
                var channelEntity = self.dao.getChannel();
                if (channelEntity.liveType == 3) {
                    $("input[name=rejectSearch]").attr("disabled","disabled");
                    $("input[name=rejectSearch]").attr("checked",true);
                }
                //self.initLocationAreaMask();
            }
        })
    }
);
define(
    '../broadcast/Broadcast.Grid',['require','exports','module'],function (require, exports, module) {
        Broadcast.Grid = function (options) {
            this.dao = Broadcast.Dao;
            this.task = Broadcast.Task;
            this.config = Broadcast.Config;
            this.options = options || {};
        };
        Com.inherits(Broadcast.Grid, Ancestor.Grid).extend({
            //===========config manager start ========================/
            runConfig: function () {
                var channelId = Com.url.getParameter("id");
                if (channelId == null || isNaN(channelId)) {
                    EpgWeb.Plugin.showTips({content: "need channelId", type: "error"})
                    return;
                }
                var self = this;
                self.$grid = $('#jqGridTable');
                self.dao.channelId = channelId;
                var taskArr = [];
                taskArr.push(self.task.getPlayPlatform(self.dao.cfgName.PlayPlatform));
                taskArr.push(self.task.getPlatSettings(self.dao.cfgName.platSettings, self.dao.channelId));

                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startConfig();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            startConfig: function () {
                var self = this;
                self.initJqGrid();
                self.initConfigForm();
            },
            initConfigForm: function () {
                var self = this;
                $("input[name^='onlineKey'][value='-1']").prop("checked", "checked");
                $("input[name^='regionKey'][value='-1']").prop("checked", "checked");
                $("input[name='checkCopyRightType'][value='-1']").prop("checked", "checked");
                $("input[name='checkBossType'][value='-1']").prop("checked", "checked");
                $("input[name='checkPublishType'][value='-1']").prop("checked", "checked");
                $("input[name=submitBtn]").bind("click", function (event) {
                    self.submitConfigForm();
                })
                var entity = self.dao.getPlatSettings().data

                $("input[name='checkCopyRightType'][value='" + entity.checkCopyRightType + "']").prop("checked", "checked");
                $("input[name='checkBossType'][value='" + entity.checkBossType + "']").prop("checked", "checked");
                $("input[name='checkPublishType'][value='" + entity.checkPublishType + "']").prop("checked", "checked");

                $.each(entity.regionLimitArr, function (i, element) {
                    $("input[name='regionKey_" + element + "'][value=1]").prop("checked", "checked");
                })
                $.each(entity.onlineLimitArr, function (i, element) {
                    $("input[name='onlineKey_" + element + "'][value=1]").prop("checked", "checked");
                })
                console.log("initForm end");
            },
            initJqGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_CONFIG);
                self.$grid.jqGrid(gridConfig);
                var responseData = self.dao.getPlatforms();
                var createDate = responseData.data;
                var fillData = {"total": 1, "page": 1, "records": createDate.length, "rows": createDate};
                self.$grid[0].addJSONData(fillData);
            },
            submitConfigForm: function () {
                var self = this;
                var entity = self.dao.createEntity();
                var onlineArr = $("input[name^='onlineKey'][value='1']:checked");
                var regionArr = $("input[name^='regionKey'][value='1']:checked");
                entity.checkCopyRightType = $("input[name='checkCopyRightType']:checked").val();
                entity.checkBossType = $("input[name='checkBossType']:checked").val();
                entity.checkPublishType = $("input[name='checkPublishType']:checked").val();
                var clientKey = "";
                $.each(onlineArr, function (i, element) {
                    clientKey = element.name.replace("onlineKey_", "")
                    entity.onlineLimitArr.push(parseInt(clientKey));
                })
                $.each(regionArr, function (i, element) {
                    clientKey = element.name.replace("regionKey_", "")
                    entity.regionLimitArr.push(parseInt(clientKey));
                })

                self.dao.doAuthData({
                    url: '/epg/config_manager.html',
                    doError:function(){
                        SystemDialog.queryAlert("很抱歉，您没有相关权限!");
                    },
                    doSuccess:function(){
                        if (EpgWeb.ajaxQueue.isRunning()) {
                            EpgWeb.Plugin.showTips({
                                content: "数据处理中，请稍后操作"
                            })
                            return;
                        }
                        var msg = self.checkDiff(entity, self.dao.getPlatSettings().data);
                        if (msg.length > 0) {
                            SystemDialog.queryConfirm(msg.join("<br>"), function (flag) {
                                if (flag === true) {
                                    self.dao.savePlatSettings( {channelId: self.dao.channelId, configData: JSON.stringify(entity)} ,function(data,submitEntity){
                                        self.settingCallBack(data,submitEntity);
                                    })
                                }
                            })
                        } else {
                            self.dao.savePlatSettings({channelId: self.dao.channelId, configData: JSON.stringify(entity)},function(data,submitEntity){
                                self.settingCallBack(data,submitEntity);
                            })
                        }
                    }
                })
            },
            settingCallBack: function (data, submitEntity) {
                var self = this;
                if (data != null) {
                    SystemDialog.queryAlert(data.msg);
                    self.dao.getPlatSettings().data = submitEntity;
                    console.log(data.code);
                } else {
                    SystemDialog.queryAlert("保存数据失败")
                    console.log(JSON.stringify(data));
                }
            },
            checkDiff: function (entity, origin) {
                var self = this;
                //权限配置
                var msg = [];
                /*
                 勾选付费：勾选后付费节目可添加至轮播台，是否确认修改？
                 勾选版权
                 勾选未发布：勾选后未发布节目可添加至轮播台，是否确认修改？
                 端选项发生变化：勾选后*端未上线的节目 *端有地域播控的节目可添加至轮播台，是否确认修改？
                 * */
                //    var origin = Broadcast.Dao,
                var typeMsg = [];
                if (entity.checkBossType == 1 && origin.checkBossType != entity.checkBossType) {
                    typeMsg.push(self.config.ERROR_MSG.bossAlertMsg)
                }
                if (entity.checkPublishType == -1 && origin.checkPublishType != entity.checkPublishType) {
                    typeMsg.push(self.config.ERROR_MSG.publishAlertMsg)
                }

                if (typeMsg.length > 0) {
                    msg.push(typeMsg.join(" "));
                }
                var responseData = self.dao.getPlatforms();
                var qiyiOnline = false;
                var ppsOnline = false;
                var qiyiRegion = false;
                var ppsRegion = false;
                $.each(responseData.data, function (index, element) {
                    //   clientArr =  [element.descr ] ;
                    if (entity.onlineLimitArr.indexOf(parseInt(element.key)) === -1 && origin.onlineLimitArr.indexOf(parseInt(element.key)) !== -1) {
                        //      clientArr.push(  Broadcast.memo.clientAlertMsg1)
                        if (element.val.indexOf("PPS") != -1) {
                            ppsOnline = true;
                        } else {
                            qiyiOnline = true;
                        }

                    }
                    if (entity.regionLimitArr.indexOf(parseInt(element.key)) === -1 && origin.regionLimitArr.indexOf(parseInt(element.key)) !== -1) {
                        //       clientArr.push(  Broadcast.memo.clientAlertMsg2)
                        if (element.val.indexOf("PPS") != -1) {
                            ppsRegion = true;
                        } else {
                            qiyiRegion = true;
                        }
                    }
                });
                //播控管理
                var clientControlArr = [];
                if (qiyiOnline || qiyiRegion) {
                    var clientArr = ["IQIYI平台"];
                    if (qiyiOnline) {
                        clientArr.push(self.config.ERROR_MSG.clientAlertMsg1)
                    }
                    if (qiyiRegion) {
                        clientArr.push(self.config.ERROR_MSG.clientAlertMsg2)
                    }
                    clientControlArr.push(clientArr.join(""))
                }
                if (ppsOnline || ppsRegion) {
                    var clientArr = ["PPS平台"];
                    if (ppsOnline) {
                        clientArr.push(self.config.ERROR_MSG.clientAlertMsg1)
                    }
                    if (ppsRegion) {
                        clientArr.push(self.config.ERROR_MSG.clientAlertMsg2)
                    }
                    clientControlArr.push(clientArr.join(""))
                }
                if (clientControlArr.length > 0) {
                    msg = msg.concat(clientControlArr);
                }
                if (msg.length > 0) {
                    msg.push("可添加至轮播台,是否确认修改?")
                }
                return msg;
            }
            //===========config manager end ========================/

        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
define(
    '../statistic/Statistic',['require','exports','module'],function (require, exports, module) {
        window.Statistic = window.Statistic || {
            version: '1.0'
        };
        Statistic.Constant = {
            baseApiUrl: "/api/",
            thirdUrl_query_user: "http://lego.iqiyi.com/external/auth/auth-api/services/user/search",
            thirdUrl_channel_type: "http://lego.iqiyi.com/suggest/operation",
            thirdUrl_query_videos: "http://lego.iqiyi.com/api/videos",

            devMode: auth.dev(),
            auth_base_url: auth.dev() ? "AUTH_channel_download_" : "AUTH_important_video_download_"
        }

        Statistic.urlConfig = (function () {
            var useUrl = Statistic.Constant.baseApiUrl;
            var sdGetUrl = useUrl + "sd";
            var queryChannelName = Statistic.Constant.devMode ? "http://10.23.70.33:7000/v1/channel/fuzzyquery" : "http://dot.live.qiyi.domain/v1/channel/fuzzyquery";
            var getVodLogUrl = useUrl + "vod/logList/legoProgramId";
            var getVodLogFilterUrl = useUrl + "vod/logList/filter";
            var getEpisodeLogUrl= useUrl + "vod/episodeLogList";
            var submitVodLogUrl = useUrl + "vod/saveLog";
            var submitEpisodeLogUrl = useUrl + "vod/saveEpisodeLog";
            return {
                sdGetUrl: sdGetUrl,
                queryChannelName: queryChannelName,
                submitVodLogUrl: submitVodLogUrl,
                submitEpisodeLogUrl: submitEpisodeLogUrl,
                getVodLogUrl: getVodLogUrl,
                getEpisodeLogUrl:getEpisodeLogUrl,
                getVodLogFilterUrl:getVodLogFilterUrl


            }
        })()
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Action.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
define(
    '../statistic/Statistic.Action',['require','exports','module'],function (require, exports, module) {
        Statistic.Action = (function () {
            var produceDataGrid

            function produceDataRun() {
                if (produceDataGrid == null) {
                    produceDataGrid = new Statistic.Grid($.extend(true, {
                        $form: $('form[name=basicFrm]'),
                        $grid: $("#VideoListGrid"),
                        $logGrid:$("#logList"),
                        $hiddenGrid: $("<table></table>"),
                        '$container': $('#VideoListContainer')
                    }, {}));
                    produceDataGrid.produceDataRun()
                    // editForm.init();
                }
                console.log(' produceDataGrid run ');
            }

            return {
                produceDataRun: produceDataRun

            }
        })()
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Config.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
define(
    '../statistic/Statistic.Config',['require','exports','module'],function (require, exports, module) {
        Statistic.Config = $.extend({}, Ancestor.Config, {
            TABLE_COLMODEL_CONFIG: {
                'addTime': {
                    name: 'addTime',
                    title: false,
                    index: 'addTime',
                    sortable: false,
                    align: 'center',
                    width: 100,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.addTime(v, o, r);
                    }
                },
                'programId': {
                    name: 'programId',
                    title: false,
                    index: 'programId',
                    align: 'center',
                    width: 100,
                    sortable: false
                },
                'qipuId': {
                    name: 'qipuId',
                    title: false,
                    index: 'qipuId',
                    sortable: false,
                    width: 100,
                    align: 'center'
                },
                'programName': {
                    name: 'programName',
                    title: false,
                    index: 'programName',
                    width: 230,
                    sortable: false,
                    align: 'center'
                },
                'programMinutes': {
                    name: 'programMinutes',
                    title: false,
                    index: 'programMinutes',
                    align: 'center',
                    sortable: false,
                    width: 100,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.programMinutes(v, o, r);
                    }
                },
                'user': {
                    name: 'user',
                    index: 'user',
                    sortable: false,
                    align: 'center',
                    width: 90
                },
                'channelName': {
                    name: 'channelName',
                    index: 'channelName',
                    sortable: false,
                    width: 130,
                    align: 'center'
                },
                'cooperativePartiner': {
                    name: 'cooperativePartiner',
                    index: 'cooperativePartiner',
                    sortable: false,
                    width: 130,
                    align: 'center'
                },
                'dotSubTime': {
                    name: 'dotSubTime',
                    index: 'dotSubTime',
                    sortable: false,
                    width: 130,
                    align: 'center'
                },
                'enterLegoTime': {
                    name: 'enterLegoTime',
                    index: 'enterLegoTime',
                    sortable: false,
                    align: 'center',
                    width: 130,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.enterLegoTime(v, r);
                    }
                },
                'legoProduceFinishedTime': {
                    name: 'legoProduceFinishedTime',
                    title: false,
                    index: 'legoProduceFinishedTime',
                    sortable: false,
                    align: 'center',
                    width: 100,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.finishedtime(v, r);
                    }
                },
                'publishTime': {
                    name: 'publishTime',
                    title: false,
                    index: 'publishTime',
                    width: 140,
                    align: 'center',
                    sortable: false
                },
                'liveBeginTime': {
                    name: 'liveBeginTime',
                    title: false,
                    index: 'liveBeginTime',
                    sortable: false,
                    align: 'center',
                    width: 130
                },
                'liveEndTime': {
                    name: 'liveEndTime',
                    title: false,
                    index: 'liveEndTime',
                    width: 140,
                    align: 'center',
                    sortable: false
                },
                ocrFlag: {
                    name: 'ocrFlag',
                    title: false,
                    index: 'ocrFlag',
                    width: 110,
                    align: 'center',
                    sortable: false,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.ocrFlag(v, o, r);
                    }
                },
                ocrTitleFlag: {
                    name: 'ocrTitleFlag',
                    title: false,
                    index: 'ocrTitleFlag',
                    width: 90,
                    align: 'center',
                    sortable: false,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.ocrTitleFlag(v, o, r);
                    }
                },

                intelligent_insert_time: {
                    name: 'intelligentInsertTime',
                    title: false,
                    index: 'intelligentInsertTime',
                    width: 130,
                    align: 'center',
                    sortable: false,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.intelligent_insert_time(v, o, r);
                    }
                },
                download: {
                    width: 200,
                    align: 'center',
                    sortable: false,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.download(v, o, r);
                    }
                },
                log_id: {
                    name: 'id',
                    index: 'id',
                    title: false,
                    sortable: false,
                    hidden: true
                },
                log_addTime: {
                    name: 'addTime',
                    index: 'addTime',
                    sortable: false,
                    title: false,
                    width: 150,
                    align: 'center'
                },
                log_user: {
                    name: 'user',
                    index: 'user',
                    sortable: false,
                    title: false,
                    width: 150
                },
                log_type: {
                    name: 'type',
                    index: 'type',
                    sortable: false,
                    title: false,
                    width: 120,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.log_type(v, o, r);
                    }
                },
                log_descr: {
                    name: "descr",
                    index: 'descr',
                    title: false,
                    width: 450,
                    sortable: false,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.log_descr(v, o, r);
                    }
                },
                dataMode: {
                    name: "dataMode",
                    index: 'dataMode',
                    width: 150,
                    align: 'center',
                    sortable: false,
                    formatter: function (v, o, r) {
                        return Statistic.Util.formatter.dataMode(v, o, r);
                    }
                }
            },

            TABLE_LIST: {
                multiselect: false,
                rowNum: 20,
                url: Statistic.urlConfig.sdGetUrl,
                colNames: ["制作日期", "节目ID", "奇谱ID", "节目原名", "节目时长(分）", "频道", "制作人员", "电视台",
                    "是否使用智能拆条","是否OCR识别", "开始打点时间",
                    "打点提交时间", "节目入乐高时间", "乐高生产状态", "直播开始时间", "直播结束时间",
                    "制作数据类型", "操作"
                ],
                colModel: ['addTime', 'programId', 'qipuId', 'programName', 'programMinutes', 'channelName', 'user', 'cooperativePartiner',
                    "ocrFlag","ocrTitleFlag", "intelligent_insert_time",
                    'dotSubTime', 'enterLegoTime', 'legoProduceFinishedTime', 'liveBeginTime', 'liveEndTime',
                    "dataMode", "download"
                ],
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                datatype: "local",
                pager: "#pager"
            },
            TABLE_LOG: {
                url: Statistic.urlConfig.getEpisodeLogUrl,
                loadBeforeSend: function (xhr, settings) {
                    var auth = Ancestor.Util.getAuth("/vod/episodeLogList");
                    xhr.setRequestHeader('Sign', auth.sign);
                    xhr.setRequestHeader("Time", auth.clientTime);
                    xhr.setRequestHeader("From", auth.from);
                    return true;
                },
                multiselect: false,
                loadtext: '加载中...',
                loadui: 'block',
                rowNum: 40,
                width: 875,
                mtype: "post",
                datatype: "local",
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                colNames: ["ID", "操作时间", "人员", "动作", "备注"],
                colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
                pager: "#log_pager"
            },

            TABLE_HIDDEN: {
                colNames: ["制作日期", "节目ID", "奇谱ID", "节目原名", "节目时长(分）", "频道", "制作人员", "电视台",
                    "是否使用智能拆条","是否OCR识别" ,"开始打点时间",
                    "打点提交时间", "节目入乐高时间", "乐高生产状态", "直播开始时间", "直播结束时间"
                ],
                colModel: ['addTime', 'programId', 'qipuId', 'programName', 'programMinutes', 'channelName', 'user', 'cooperativePartiner',
                    "ocrFlag","ocrTitleFlag", "intelligent_insert_time",
                    'dotSubTime', 'enterLegoTime', 'legoProduceFinishedTime', 'liveBeginTime', 'liveEndTime'
                ]
            },
            FINISHED_STATUS: ["未制作", "制作完成", "制作中", "制作异常", "流程被终止"],
            PUBLISH_STATUS: ["未发布", "已发布", "页面下线", "页面备用"],
            VOD_LOG_TYPE: {
                redoSubmit:109,
                sendToLego:106,
                delayWrapDataToLego:122,
                sendWrapDataToLego: 123,
                notifyWrapPublish:124,
                sendWrapDataToLego_suc: 125,
                sendWrapDataToLego_fail: 126,
                selectSendMode:127
            },
            STATISTIC_DATA_MODE:{
                original:0,  //0：纯净版,
                fragment_wrap_new:89,  // 89:新建包装版-分片,
                fragment_wrap_not_made:90,   // 90:包装覆盖未制作-分片
                fragment_wrap_made:91,    // 91：包装覆盖已制作-分片,
                wrap_new:99,  // 99:新建包装版,
                wrap_not_made:100,  // 100:包装覆盖未制作，
                wrap_made:101  // 101：包装覆盖已制作
            }
        })


    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Dao.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
define(
    '../statistic/Statistic.Dao',['require','exports','module'],function (require, exports, module) {
        Statistic.Dao = $.extend({}, EpgWeb.Dao, {
            cfgName: {
                LogType: "vod_log"
            },
            getChannelType: function (handler) {
                var ajaxOptions = {
                    type: "post",
                    url: EpgWeb.urlConfig.redirect,
                    dataType: "json",
                    data: {"request": JSON.stringify({url: Statistic.Constant.thirdUrl_channel_type, type: "get", params: {size: 100}, needCookie: true}), timeSign: new Date().getTime()},
                    success: function (data) {
                        var formatData = [];
                        $.each(data.data, function (i, element) {
                            formatData.push({id: element.id, label: element.name, value: element.name})
                        })
                        handler(formatData);
                        console.log("renderPanel happen");
                    },
                    error: function (data) {
                        console.log("error happen");
                    }
                };
                $.ajax(ajaxOptions)
            },

            getExportData: function (data, callback) {
                var options = {
                    url: Statistic.urlConfig.sdGetUrl,
                    dataType: 'json',
                    data: data,
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/sd');
            },
            getExportDataAll: function (params, handler) {
                var daoSelf = this;
                params.pageNo = 1;
                handler.lockHandler();
                var queryComponent = {
                    params: params,
                    dataArr: [],
                    phase: 0,
                    hasFlushNum: 0,
                    query: function () {
                        var self = this;
                        daoSelf.getExportData(params, function (data) {
                            if (data == null) {
                                EpgWeb.Plugin.showTips({content: "请求失败", type: "error"  })
                                handler.phaseHandler(self.dataArr);
                                handler.unlockHandler();
                            } else {
                                self.dataArr = self.dataArr.concat(data.data.result);
                                self.phase++;
                                handler.phaseHandler(self.dataArr, "phase" + self.phase);
                                console.log("self.phase:" + self.phase);
                                self.hasFlushNum += self.dataArr.length;
                                self.dataArr = [];
                                if (self.hasFlushNum < data.data.totalCount) {
                                    self.params["pageNo"] = params.pageNo + 1;
                                    console.log("params.pageNo:" + self.params["pageNo"]);
                                    self.query();
                                } else {
                                    handler.unlockHandler();
                                }
                            }
                        })
                    }
                };
                queryComponent.query();
            },
            postSync: function (postUrl, postData, handler, sync) {
                var async = sync == null ? true : sync != true;
                var options = {
                    cache: false,
                    async: async,
                    type: "post",
                    dataType: "json",
                    url: postUrl,
                    data: postData,
                    success: function (res) {
                        handler.doSuc(res);
                    },
                    error: function () {
                        handler.doError();
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            submitLogEntity: function (data, callback) {
                var url = Statistic.urlConfig.submitVodLogUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(data)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/vod/saveLog");
            },
            submitEpisodeLogEntity: function (data, callback) {
                var url = Statistic.urlConfig.submitEpisodeLogUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(data)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/vod/saveEpisodeLog");
            },
            logType: function () {
                return this.getDataByName(this.cfgName.LogType);
            },

            makeOptionsCheckLegoVideoData: function (programId) {
                var self = this;
                return {
                    type: "get",
                    url: Statistic.Constant.thirdUrl_query_videos,
                    dataType: "json",
                    data: {filter: {EQL_entityId: "" + programId}, page: {pageSize: 2, pageNo: 1, orderBy: "createTime", order: "desc"}},
                    beforeQuery: function (options, resultData) {
                        console.log("beforeQuery " + JSON.stringify(resultData));
                        var newOptions = self.transToProxyOptions(options, {Sign: "#f93Uc31K24()_@"})
                        return newOptions;
                    },
                    judge: function (data) {
                        if (data != null && data.code == "A00000") {
                            if (data.data.result.length == 1) {
                                var isReTranscode = Statistic.Util.isAvailableForReTranscode(data.data.result[0]);
                                if (!isReTranscode) {
                                    EpgWeb.Plugin.showTips({type: "error", content: "当前节目不支持重新发布"});
                                }
                                return isReTranscode;
                            }
                            return false;
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: Statistic.Constant.thirdUrl_query_videos + " 接口请求失败:" + JSON.stringify(data)});
                            return false;
                        }
                    }
                }
            },

            makeOptionsGetEpisodeLogList: function (programId, typeValues, descrLikes) {
                var paramsObj = {EQL_programId: "" + programId, INI_type: typeValues}
                if (descrLikes != null) {
                    paramsObj["LIKES_description"] = descrLikes
                }
                var sendData = { pageSize: 20, pageNo: 1, paramsObj: JSON.stringify(paramsObj), timeSign: Date.now() };
                var options = {
                    url: Statistic.urlConfig.getEpisodeLogUrl,
                    dataType: 'json',
                    data: sendData,
                    type: 'post',
                    judge: function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({type: "error", content: "/api/vod/episodeLogList 无响应"});
                        } else if (data.code == "A00000") {
                            return true;
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: data.msg});
                        }
                        return false;
                    }
                }
                return this.appendAuthUrl(options, '/vod/episodeLogList');
            },
            makeOptionsGNotifyLegoRemake: function (needResultKey, overrideData) {
                return  {
                    type: "post",
                    url: EpgWeb.urlConfig.redirect,
                    dataType: "json",
                    needResult: needResultKey,
                    checkNeedResult: function (resultData) {
                        var dataArr = resultData.data.result;
                        if (dataArr != null && dataArr.length > 0) {
                            var type = dataArr[0].type;
                            return type == Statistic.Config.VOD_LOG_TYPE.delayWrapDataToLego
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: "缺少延时发送lego 日志数据"});
                        }
                        return false;
                    },
                    beforeQuery: function (options, resultData) {
                        console.log("beforeQuery " + JSON.stringify(resultData));
                        var dataArr = resultData.data.result;
                        var selectElement = dataArr[0].descr;
                        var programId = dataArr[0].programId;
                        var type = dataArr[0].type;
                        // type == Statistic.Config.VOD_LOG_TYPE.delayWrapDataToLego
                        var elementArr = selectElement.split("|");
                        var retVal = elementArr.shift();
                        var oldUrl = elementArr.shift().substring(4);
                        var sendData = JSON.parse(elementArr.join("|"));
                        if (overrideData != null) {
                           // sendData = $.extend({}, sendData, overrideData);
                            sendData =   Statistic.Util.decodeSendLegoData( sendData ,overrideData )
                        }
                        var newOptions = $.extend({}, options, {
                            data: sendData,
                            success: function (data) {
                                options.success(data);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.sendWrapDataToLego_suc, sendData, data, "fromUrl:" + oldUrl);
                            }, error: function (XMLHttpRequest, status) {
                                options.error(null);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.sendWrapDataToLego_fail, sendData, { type: "error reqeust", status: status }, "fromUrl:" + oldUrl);
                            }
                        });
                        return newOptions;
                    },
                    judge: function (data) {
                        if (data != null && data.code == 'A00000') {
                            if (data.data.programId != null && data.data.programId > 0) {
                                return true;
                            } else {
                                EpgWeb.Plugin.showTips({type: "error", content: "lego节目ID 返回为空"});
                            }
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: "lego接口无效返回值"});
                        }
                        return false;
                    }
                }
            },
            makeOptionsDadianPublish: function (needResultkey, overrideData) {
                return  {
                    type: "post",
                    url: EpgWeb.urlConfig.redirect,
                    dataType: "json",
                    needResult: needResultkey,
                    checkNeedResult: function (resultData) {
                        var dataArr = resultData.data.result;
                        return dataArr != null && dataArr.length > 0;
                    },
                    beforeQuery: function (options, resultData) {
                        console.log("beforeQuery " + JSON.stringify(resultData));
                        var dataArr = resultData.data.result;
                        var selectElement = dataArr[0].descr;
                        var channelId = dataArr[0].channelId;
                        var programId = dataArr[0].programId;
                        var elementArr = selectElement.split("|");
                        var retVal = elementArr.shift();
                        var oldUrl = elementArr.shift().substring(4);
                        var sendUrl = oldUrl.split("/dot")[0] + "/dot/publish";
                        var params = {programId: programId, from_client: true};
                        if (overrideData != null) {
                            params = $.extend({}, params, overrideData);
                        }
                        var newOptions = $.extend({}, options, {
                            url: sendUrl,
                            data: params,
                            success: function (data) {
                                options.success(data);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.notifyWrapPublish, params, data, "fromUrl:" + sendUrl);
                            }, error: function (XMLHttpRequest, status) {
                                options.error(null);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.notifyWrapPublish, params, null, "fromUrl:" + sendUrl);
                            }
                        });
                        return newOptions;
                    },
                    judge: function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({type: "error", content: "/dot/publish 接口请求失败!"});
                        } else if (data.error != null && parseInt(data.error) == 0) {
                            EpgWeb.Plugin.showTips({ content: "请求成功"});
                            return true;
                        } else {
                            EpgWeb.Plugin.showTips({ content: "请求失败:" + JSON.stringify(data)});
                        }
                        return false;
                    }
                }
            },
            makeOptionsCheckHasSendLego: function (programId, typeValues, descrLikes) {
                var paramsObj = {EQL_programId: "" + programId, INI_type: typeValues}
                if (descrLikes != null) {
                    paramsObj["LIKES_description"] = descrLikes
                }
                var sendData = { pageSize: 20, pageNo: 1, paramsObj: JSON.stringify(paramsObj), timeSign: Date.now() };
                var options = {
                    url: Statistic.urlConfig.getEpisodeLogUrl,
                    dataType: 'json',
                    data: sendData,
                    type: 'post',
                    judge: function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({type: "error", content: "/api/vod/episodeLogList 无响应"});
                        } else if (data.code == "A00000") {

                            return true;
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: data.msg});
                        }
                        return false;
                    }
                }
                return this.appendAuthUrl(options, '/vod/episodeLogList');
            }
        })

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Util.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
define(
    '../statistic/Statistic.Util',['require','exports','module'],function (require, exports, module) {
        Statistic.Util = $.extend(true, {}, EpgWeb.Util, {
            formatter: {
                download: function (v, o, r) {
                    var htmlArr = [];
//                  if (r.legoProduceFinishedTime !== "1" && Statistic.Util.checkRedoTime(r.addTime)) {
//                      htmlArr.push('<a href="javascript:;" onclick="Statistic.Util.redoReadLog( ' + r.programId + ',\'' + r.addTime + '\'   )">重启制作</a>');
//                    }
                    htmlArr.push('<a href="javascript:;" onclick="Statistic.Util.goToDownload( ' + r.programId + ',\'' + r.channelName + '\' )">下载</a>');
                    htmlArr.push('<a href="javascript:;" onclick="Statistic.Util.openHistory( ' + r.programId + ' )">日志</a>');
                    var result = Statistic.Util.switchWrapSend(r);
                    if (result.length > 0) {
                        htmlArr.push(result);
                    }
                    return htmlArr.join("&nbsp;");
                },
                addTime: function (v, o, r) {
                    return v.substring(0, 10);
                },
                ocrFlag: function (v, o, r) {
                    return v == 0 ? "否" : "是"
                },
                ocrTitleFlag: function (v, o, r) {
                    return v == 0 ? "否" : "是"
                },
                intelligent_insert_time: function (v, o, r) {
                    return v == null ? "" : v;
                },
                enterLegoTime: function (v, r) {
                    return v == null ? "" : v;
                },
                finishedtime: function (v, r) {
                    var rt = Statistic.Config.FINISHED_STATUS[r.legoProduceFinishedTime];
                    if (rt === undefined) {
                        rt = "";
                    }
                    return  rt;
                },
                programMinutes: function (v, o, r) {
                    //   var duration = parseInt((v * 60).toFixed(0));
                    var duration = v;
                    var darArr = [];
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration);

                    var retValue = "";
                    switch (darArr.length) {
                        case 3:
                            retValue += darArr[2] <= 0 ? "" : darArr[2] + "时";
                        case 2:
                            retValue += darArr[1] <= 0 ? "" : darArr[1] + "分";
                        case 1:
                            retValue += darArr[0] <= 0 ? "" : darArr[0] + "秒";
                            break;
                    }
                    if (retValue.length == 0) {
                        retValue = "0秒";
                    }
                    return retValue;
                },
                purchase: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    switch (checkValue) {
                        case 0:
                        case -100:
                            return "免费";
                        case 1:
                            return "收费";
                        default:
                            return checkValue + ""
                    }
                },
                publishStatus: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    switch (checkValue) {
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                            return  Statistic.Config.PUBLISH_STATUS[checkValue];
                        default:
                            return checkValue + "";
                    }
                },
                log_type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Statistic.Dao.logType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                },
                log_descr: function (cellvalue, options, rowObject) {
                    var ret = cellvalue;
                    if (rowObject.type == 107 || rowObject.type == 108) {
                        ret = Statistic.Util.decodeDescription(cellvalue)
                    }
                    return  ret;
                },
                dataMode: function (cellvalue, options, rowObject) {
                    var ret = "";
                    switch (cellvalue) {
                        case Statistic.Config.STATISTIC_DATA_MODE.original:
                            ret = "纯净版";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_new:
                            ret = "新建包装版-分片";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_not_made:
                            ret = "包装覆盖未制作-分片";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_made:
                            ret = "包装覆盖已制作-分片";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.wrap_new:
                            ret = "新建包装版";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.wrap_not_made:
                            ret = "包装覆盖未制作";
                            break;
                        case Statistic.Config.STATISTIC_DATA_MODE.wrap_made:
                            ret = "包装覆盖已制作";
                            break;
                        default :
                            ret = "旧数据类型" + cellvalue;
                            break;
                    }
                    return ret;
                }
            },
            goToDownload: function (id, channelName) {
                var legoData = Statistic.Dao.getDataByName("legoChannelId");
                if (legoData == null) {
                    EpgWeb.Plugin.showTips({type: "error", content: "lego接口异常"})
                    return;
                }
                var channelData = null;
                $.each(legoData.data, function (i, element) {
                    if (element.name == channelName) {
                        channelData = element;
                        return true;
                    }
                })
                Statistic.Dao.doAuthData({
                    url: Statistic.Constant.auth_base_url + channelData.id,
                    doError: function () {
                        EpgWeb.Plugin.showTips({type: "error", content: "用户没有 " + channelName + " 下载权限"});
                    },
                    doSuccess: function () {
                        window.open('http://lego.iqiyi.com/material/download?id=' + id + '&entityType=0', '_target')
//  + '<a data-url-id='+r.programId+' style="display:none" target="_new" href="http://lego.iqiyi.com/material/download?id=' + r.programId + '&entityType=0">下载</a>'
                        // $("a[data-url-id="+id+"]").click();
                    }
                })
            },
            checkRedoTime: function (addTime) {
                var currentTime = new Date();
                var queryTime = new Date(addTime.replace(/-/g, "/"));
                return  ( queryTime.getTime() >= currentTime.getTime() - 3 * 86400000 )
            },

            doFragmentPublishProcess: function (programId, addTime) {
                var process = new Statistic.Process({regKey: "" + programId });
                var node3 = {key: "queryList2", nextKey: "sendPublish", root: true}
                var node5 = {key: "sendPublish"}
                //node3
                process.addProcessTree(node3);
                process.addOrderFunObj(node3.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "108", "/dot/append2"))
                //node5
                process.addProcessTree(node5);
                process.addOrderFunObj(node5.key, Statistic.Dao.makeOptionsDadianPublish("queryList2"))
                process.startProcess();
            },
            doIntegralNewProcess: function (programId, addTime) {
                this.redoPublishProcess(programId, addTime);
            },
            doIntegralUnMadeProcess: function (programId, mode, addTime) {
                console.log("mode:" + mode);
                var modeStr = "";
                var hintMsg = "";
                if (mode == 1) {
                    modeStr = "仅包装发布";
                    hintMsg = "是否确认仅包装发布"
                } else if (mode == 2) {
                    modeStr = "覆盖包装发布";
                    hintMsg = "是否确认覆盖包装发布"
                }
                var handler = function (resultData) {
                    Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.selectSendMode,
                        {
                            user: auth.baseInfo.authInfo.email,
                            mode: modeStr
                        },
                        resultData, "");
                }
                SystemDialog.queryConfirm(hintMsg, function (flag) {
                    if (flag == true) {
                        if (mode == 2) {
                            Statistic.Util.redoPublishProcess(programId, addTime, handler,{"reTranscodeConfirm":1})
                        } else {
                            Statistic.Util.doDirectPublishProcess(programId, addTime, handler);
                        }
                    }
                })
            },
            doIntegralMadeProcess: function (programId, addTime) {
                this.redoPublishProcess(programId, addTime);
            },
            redoPublishProcess: function (programId, addTime, handler ,overrideData) {
                var process = new Statistic.Process({regKey: "" + programId, handler: handler  });
                //  var node6 = {key: "checkSendLego", nextKey: "checkLegoVideoData", root: true};
                var node1 = {key: "checkLegoVideoData", nextKey: "queryList1", root: true};
                var node2 = {key: "queryList1", nextKey: "queryList2"}
                var node3 = {key: "queryList2", nextKey: "sendLegoRemake"}
                var node4 = {key: "sendLegoRemake", nextKey: "sendPublish"}
                var node5 = {key: "sendPublish"}
                // node1;
                process.addProcessTree(node1);
                process.addOrderFunObj(node1.key, Statistic.Dao.makeOptionsCheckLegoVideoData(programId));
                // node2;
                process.addProcessTree(node2);
                process.addOrderFunObj(node2.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "122"))
                //node3
                process.addProcessTree(node3);
                process.addOrderFunObj(node3.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "107,108", "/dot/append2"))
                //node4
                process.addProcessTree(node4);
                process.addOrderFunObj(node4.key, Statistic.Dao.makeOptionsGNotifyLegoRemake("queryList1",overrideData))
                //node5
                process.addProcessTree(node5);
                process.addOrderFunObj(node5.key, Statistic.Dao.makeOptionsDadianPublish("queryList2",overrideData))
                process.startProcess();
            },

            doDirectPublishProcess: function (programId, addTime, handler) {
                var process = new Statistic.Process({regKey: "" + programId, handler: handler});
                var node2 = {key: "queryList1", nextKey: "queryList2", root: true}
                var node3 = {key: "queryList2", nextKey: "sendLegoRemake"}
                var node4 = {key: "sendLegoRemake", nextKey: "sendPublish"}
                var node5 = {key: "sendPublish"}
                // node2;
                process.addProcessTree(node2);
                process.addOrderFunObj(node2.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "122"))
                //node3
                process.addProcessTree(node3);
                process.addOrderFunObj(node3.key, Statistic.Dao.makeOptionsGetEpisodeLogList(programId, "107,108", "/dot/append2"))
                //node4
                process.addProcessTree(node4);
                process.addOrderFunObj(node4.key, Statistic.Dao.makeOptionsGNotifyLegoRemake("queryList1"))
                //node5
                process.addProcessTree(node5);
                process.addOrderFunObj(node5.key, Statistic.Dao.makeOptionsDadianPublish("queryList2"))
                process.startProcess();
            },
            decodeSendLegoData:function(sendData,overrideData){
                var requestData = JSON.parse(sendData.request);
                var toLegoData =  JSON.parse(requestData.params.data);
                toLegoData = $.extend({},toLegoData,overrideData);
                requestData.params.data = JSON.stringify(toLegoData);
                sendData.request = JSON.stringify(requestData);
                return sendData;
            },
            decodeDescription: function (description) {
                var elementArr = description.split("|");
                var newArr = [];
                if (elementArr.length == 2) {
                    newArr.push(elementArr.shift());
                } else if (elementArr.length >= 3) {
                    newArr.push(elementArr.shift());
                    newArr.push(elementArr.shift());
                }
                var jsonObj = JSON.parse(elementArr.join("|"));
                var list = JSON.parse(jsonObj.list);
                if (list.length > 2) {
                    var newFold = [];
                    var nodeStart = -100;
                    var nodeEnd = -100;
                    var curIndex = 0;
                    $.each(list, function (i, element) {
                        curIndex = element;
                        if (curIndex > nodeEnd + 1) {
                            if (nodeStart >= 0) {
                                newFold.push({ start: nodeStart, end: nodeEnd});
                            }
                            nodeStart = curIndex;
                            nodeEnd = curIndex;
                        } else if (curIndex == nodeEnd + 1) {
                            nodeEnd = curIndex;
                        }
                    })
                    if (nodeEnd >= nodeStart) {
                        newFold.push({ start: nodeStart, end: nodeEnd});
                    }
                    jsonObj.list = newFold;
                }
                newArr.push(JSON.stringify(jsonObj));
                return newArr.join("|");
            },
            episodeLogSubmit: function (programId, type, params, response, plusMsg) {
                var submitData = {
                    programId: programId,
                    type: type,
                    user: auth.baseInfo.authInfo.email,
                    descr: JSON.stringify(response) + ( plusMsg == null ? "" : "|" + plusMsg) + "|" + JSON.stringify(params) };
                Statistic.Util.doSubmitEpisodeLogEntity(submitData);
                if(type == Statistic.Config.VOD_LOG_TYPE.sendWrapDataToLego_suc){
                    if(null == params.paramType){
                        console.log("old data has no isAppendFragementFlag");
                        return ;
                    }else{
                        var tempData = {
                            success: true,
                            funcType: "create_video",
                            sendData: JSON.stringify(params),
                            plusMsg: plusMsg,
                            response: response,
                            programId: programId,
                            serverIp: params.serverIp,
                            paramType: params.paramType
                        }
                        EpgWeb.PingBack.doQuickSend(tempData);
                        tempData = null;
                    }
                }
            },
            doSubmitEpisodeLogEntity: function (submitLogData) {
                Statistic.Dao.submitEpisodeLogEntity(submitLogData, function (data) {
                        if (data == null || data.code != "A00000") {
                            console.warn("SubmitEpisodeLogEntity error");
                        } else {
                            console.log("SubmitEpisodeLogEntity suc");
                        }
                    }
                )
            },
            openHistory: function (entityId) {
                $("#vodEpisodeLogDiv").dialog("open");
                $('#logList').jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {paramsObj: JSON.stringify({ EQL_programId: entityId})}
                }).trigger('reloadGrid');
            },
            buildTH: function (dataArr) {
                var retValue = [];
                $.each(dataArr, function (i, element) {
                    retValue.push("<td>" + element + "</td>");
                });
                return "<tr>" + retValue.join("") + "</tr>";
            },
            buildTD: function (object, keyArr) {
                var retValue = [];
                $.each(keyArr, function (index, element) {
                    var configData = Statistic.Config.TABLE_COLMODEL_CONFIG[element];
                    if (configData.formatter != null) {
                        retValue.push("<td>" + configData.formatter(object[configData.name], null, object) + "</td>");
                    } else {
                        retValue.push("<td>" + object[configData.name] + "</td>");
                    }
                });
                return "<tr>" + retValue.join("") + "</tr>";
            },
            // 乐高 重转 js 判断
            isAvailableForReTranscode: function (data) {
                var isPurchase = data.isPurchase;
                var freeTypeStatus = data.freeTypeStatus;
                var canBeTranscode = data.canBeTranscode;
                var isMainChannel = data.isMainChannel;
                //重转处理完成 并处于待划价时， 置灰重转链接
                if (isPurchase == "1" && freeTypeStatus == "3") {
                    return false;
                }
                // 是主频道并可以重转时 重转可用
                if (canBeTranscode && (isMainChannel == 1)) {
                    return true;
                }
                return false;
            },
            // 乐高 非编 js 判断
            isAvailableForNonlinear: function (data) {
                var isPurchase = data.isPurchase;
                var freeTypeStatus = data.freeTypeStatus;
                var canBeMake = data.canBeMake;
                var isMainChannel = data.isMainChannel;
                //重转处理完成 并处于待划价时， 置灰非编链接
                if (isPurchase == "1" && freeTypeStatus == "3") {
                    return false;
                }
                // 是主频道并可以重转时 重转可用
                if (canBeMake && (isMainChannel == 1)) {
                    return true;
                }
                return false;
            },
            switchWrapSend: function (statisticData) {
                var ret = "";
                switch (statisticData.dataMode) {
                    case 0:
                        break;
//                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_new:
////                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_not_made:
////                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_made:
//                        ret = '<a href="javascript:;" onclick="Statistic.Util.doFragmentPublishProcess( ' + statisticData.programId + ',\'' + statisticData.addTime + '\'   )">分片包装发布</a>'
//                        break;
//                    case Statistic.Config.STATISTIC_DATA_MODE.wrap_new:
//                        ret = '<a href="javascript:;" onclick="Statistic.Util.doIntegralNewProcess( ' + statisticData.programId + ',\'' + statisticData.addTime + '\'   )">新建包装发布</a>'
//                        break;
                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_not_made:
                    case Statistic.Config.STATISTIC_DATA_MODE.wrap_not_made:
                        ret = '<a href="javascript:;" onclick="Statistic.Util.doIntegralUnMadeProcess( ' + statisticData.programId + "," + 2 + ',\'' + statisticData.addTime + '\'   )">覆盖包装发布</a>&nbsp;' +
                            '<a href="javascript:;" onclick="Statistic.Util.doIntegralUnMadeProcess( ' + statisticData.programId + "," + 1 + ',\'' + statisticData.addTime + '\'   )">仅包装发布</a>'
                        break;
                    case Statistic.Config.STATISTIC_DATA_MODE.fragment_wrap_made:
                    case Statistic.Config.STATISTIC_DATA_MODE.wrap_made:
                        ret = '<a href="javascript:;" onclick="Statistic.Util.doIntegralMadeProcess( ' + statisticData.programId + ',\'' + statisticData.addTime + '\'   )">覆盖包装发布</a>'
                        break;
                }
                return ret;
            }
        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Grid.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
define(
    '../statistic/Statistic.Grid',['require','exports','module'],function (require, exports, module) {

        Statistic.Grid = function (options) {
            this.dao = Statistic.Dao;
            this.config = Statistic.Config;
            this.options = options || {};
            this.exportExcel = false;
        };
        Com.inherits(Statistic.Grid, Ancestor.Grid).extend({
            produceDataRun: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.$form = self.options.$form;
                self.$hiddenGrid = self.options.$hiddenGrid;
                self.$logGrid = self.options.$logGrid;
                var taskArr = [];
                var task = {
                    regName: "legoChannelId",
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.redirect,
                        dataType: "json",
                        data: {"request": JSON.stringify({url: Statistic.Constant.thirdUrl_channel_type, type: "get", params: {size: 100}, needCookie: true}), timeSign: new Date().getTime()}
                    }
                };
                taskArr.push(task);
                taskArr.push( EpgWeb.Task.getConfigType(self.dao.cfgName.LogType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.initSuggest();
                    self.startGrid();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            startGrid: function () {
                var self = this;
                self.initQueryDate();
                self.bindBasicEvent();
                self.initDlg();
                self.initGrid();
                self.initLogGrid();
            },
            initDlg:function(){
                $("#vodEpisodeLogDiv").dialog({
                    title: "历史记录",
                    autoOpen: false,
                    width: 900,
                    height: 600,
                    modal: true,
                    dialogClass: 'alert'
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            initGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                self.$grid.jqGrid(gridConfig);
                self.echoQuery();
            },

            initLogGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LOG);
                self.$logGrid.jqGrid(gridConfig);
            },

            checkBeforeQuery: function (params) {
                var sMinsStr = typeof params.sPrMins == "string";
                var eMinsStr = typeof params.ePrMins == "string";
                if (sMinsStr && params.sPrMins.length > 0 && !EpgWeb.Plugin.Validate.checkNum(params.sPrMins)) {
                    EpgWeb.Plugin.showTips({type: "error", content: "节目时长需要非负整数"})
                    return false;
                }
                if (eMinsStr && params.ePrMins.length > 0 && !EpgWeb.Plugin.Validate.checkNum(params.ePrMins)) {
                    EpgWeb.Plugin.showTips({type: "error", content: "节目时长需要非负整数"})
                    return false;
                }

                if ((params.sPrMins + "").length > 0 && (params.ePrMins + "").length > 0) {
                    if (parseInt(params.ePrMins) <= parseInt(params.sPrMins)) {
                        EpgWeb.Plugin.showTips({type: "error", content: "节目时长范围错误"})
                        return false;
                    }
                }
                return true;
            },
            getParam: function () {
                var self = this;
                var params = {};
                params.cname = $("input[name=cname]").val();
                var $form = self.options.$form;
                var sPrMins = $("input[name=sPrMins]").val();
                var ePrMins = $("input[name=ePrMins]").val();
                params.sPrMins = sPrMins;
                params.ePrMins = ePrMins;
                if (EpgWeb.Plugin.Validate.checkNum(sPrMins)) {
                    params.sPrMins = parseInt(sPrMins) * 60;
                }
                if (EpgWeb.Plugin.Validate.checkNum(ePrMins)) {
                    params.ePrMins = parseInt(ePrMins) * 60;
                }
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });
                var filterNameArr = ["cname", "sPrMins", "ePrMins"];
                $.each($elements, function (i, element) {
                    if (element.type == "text") {
                        if (filterNameArr.indexOf(element.name) == -1) {
                            params[element.name] = $.trim($(element).val()) || '';
                        }
                    }
                });
                params.type = "pd";
                params.ocrFlag = $("select[name=is_ocr_flag]").val();
                params.ocrTitleFlag = $("select[name=is_ocr_title_flag]").val();
                //ocrTitleFlag
                return params;
            },
            initQueryDate: function () {
                var currentDate = new Date(), beginDateTime = new Date(), endDateTime = new Date();
                Statistic.Util.setZeroTime(currentDate);
                endDateTime.setTime(currentDate.getTime() + 86400000);
                beginDateTime.setTime(endDateTime.getTime() - 7 * 86400000);
                var searchBegin = Statistic.Util.formatDateTimeFormat(beginDateTime);
                var searchEnd = Statistic.Util.formatDateTimeFormat(endDateTime);
                Statistic.Util.bindDate("b_date", "e_date", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchBegin, minDateTime: new Date(searchBegin.replace(/-/g, "/")) });
                $("input[name=e_date]").datetimepicker("setDate", endDateTime);
                $("input[name=b_date]").datetimepicker("setDate", beginDateTime);

                Statistic.Util.bindDate("live_b_date", "live_e_date", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchBegin, minDateTime: new Date(searchBegin.replace(/-/g, "/")) });
                $("input[name=live_e_date]").datetimepicker("setDate", endDateTime);
                $("input[name=live_b_date]").datetimepicker("setDate", beginDateTime);
            },
            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;
                $container.find("button.query-btn").bind("click", function (event) {
                    self.query();
                    return false;
                })
                $container.find("button.query-excel").bind("click", function (event) {
                    self.$hiddenGrid.html("");
                    $("button.query-excel").prop("disabled", "disabled")
                    self.doExportExcel();
                })
                $container.find("button[name=resetBtn]").bind("click", function (event) {
                    self.$form[0].reset();
                    self.initQueryDate();
                })
            },
            doExportExcel: function () {
                var self = this;
                var params = self.getParam();
                if (!self.checkBeforeQuery(params)) {
                    return;
                }
                params.pageSize = 5000;
                self.dao.getExportDataAll(params, {
                    lockHandler: function () {
                        $("button.query-excel").prop("disabled", "disabled")
                    },
                    flushCheck: function (curNum) {
                        return curNum >= 5000
                    },
                    phaseHandler: function (dataArr, fileName) {
                        self.doExportExcelAllCallBack(dataArr, fileName);
                    },
                    unlockHandler: function () {
                        $("button.query-excel").removeAttr("disabled")
                    }
                });
            },
            doExportExcelAllCallBack: function (dataArr, fileName) {
                var self = this
                if (dataArr != null && dataArr.length > 0) {
                    self.$hiddenGrid.append(Statistic.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(dataArr, function (i, element) {
                        self.$hiddenGrid.append(Statistic.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                if (fileName != null) {
                    EpgWeb.Plugin.tableToExcel({nodeType: true, innerHTML: self.$hiddenGrid.html()}, fileName)
                    //    self.$hiddenGrid.tableToExcel({name: fileName});
                } else {
                    EpgWeb.Plugin.tableToExcel({nodeType: true, innerHTML: self.$hiddenGrid.html()}, "制作数据统计")
                    // self.$hiddenGrid.tableToExcel();
                }
                self.$hiddenGrid.html("");
            },
            doExportExcelCallBack: function (data) {
                var self = this
                if (data != null && data.data.result.length > 0) {
                    self.$hiddenGrid.append(Statistic.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(data.data.result, function (i, element) {
                        self.$hiddenGrid.append(Statistic.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                //      self.$hiddenGrid.tableToExcel();
                EpgWeb.Plugin.tableToExcel({nodeType: true, innerHTML: self.$hiddenGrid.html()}, "制作数据统计")
                self.$hiddenGrid.html("");
                console.log("excel build end");
                $("button.query-excel").removeAttr("disabled")
            },
            echoQuery: function () {
                var self = this;
                self.query();
            },
            query: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                if (!self.checkBeforeQuery(params)) {
                    return;
                }
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    mtype: 'get',
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            initSuggest: function () {
                var self = this;
                var channelTypeSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        renderPanel: function (handler) {
                            self.dao.getChannelType(handler)
                        },
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {size: 100} : {word: term, size: 100}
                            var requestData = {url: Statistic.Constant.thirdUrl_channel_type, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }

                $("input[name=cname]").suggest(channelTypeSuggest.options);
                $("input[name=cname]").suggest("setSelectedItem", null);

                var prNameSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_video_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["entityId"];
                                itemData[options.labelKey] = item["properTitle"];
                                itemData[self._displayKey] = item["entityId"];
                                itemData["channelName"] = item["channelName"];
                                itemData["globalPublishDate"] = item["globalPublishDate"] || "";
                                itemData["isPurchase"] = item["isPurchase"];
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            var formatArr = [];
                            formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
                            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
                            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
                            formatArr.push('<span class="contract-width120">' + item.globalPublishDate + '</span>');
                            formatArr.push('<span class="contract-width80">' + Statistic.Util.formatter.purchase(item.isPurchase) + '</span>');
                            formatArr.push('<span class="contract-width80">' + Statistic.Util.formatter.publishStatus(item.pagePublishStatus) + '</span>');
                            return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                        },
                        header: '<div class="contract-item" >' +
                            '<span class="contract-width100">节目Id</span>' +
                            '<span class="contract-width150">节目显示名称</span>' +
                            '<span class="contract-width60">频道</span>' +
                            '<span class="contract-width120">发行时间</span>' +
                            '<span class="contract-width80">是否付费</span>' +
                            '<span class="contract-width80">发布状态</span></div>'
                    }
                };

                $("input[name=pr_name]").suggest(prNameSuggest.options);


                var fuzzyQuerySuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Statistic.urlConfig.queryChannelName, type: "get", params: {keyword: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === 200) {
                                data = json.response.list == null ? null : json.response.list;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["channel_name"];
                                itemData[options.labelKey] = item["channel_name"];
                                itemData[self._displayKey] = item["channel_name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["id"];
                        }
                    }
                }
                $("input[name=cp]").suggest(fuzzyQuerySuggest.options);

                var emailSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Statistic.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=u]").suggest(emailSuggest.options);
            }


        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Util.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2017-10-25
 */
define(
    '../statistic/Statistic.Process',['require','exports','module'],function (require, exports, module) {
        Statistic.Process = function (options) {
            this.regKey = options.regKey;
            this.logEntity = {
                logArr: [],
                push: function (logData) {
                    this.logArr.push(logData);
                }
            }
            this.isStop = false;
            this.statusDescr = null;
            this.timerId = -1;
            this.treeObj = {};
            this.methodObj = {};
            this.rootKey = null;
            this.currentKey = null;
            this.finalHandler = function(resultData){
                if( typeof (options.handler) ){
                    options.handler(resultData);
                }
            };
        }
        Com.inherits(Statistic.Process, {}).extend({
            startProcess: function () {
                console.log("[regKey=" + this.regKey + "]process start");
                var self = this;
                if (self.timerId != -1) {
                    clearInterval(self.timerId);
                }
                self.timerId = setInterval(function () {
                    if (!self.isStop && !self.isWork) {
                        self.callNext(self.currentKey)
                    }
                }, 300)
            },
            stopProcess: function () {
                clearInterval(this.timerId);
                this.isStop = true;
                this.isWork = false;
                console.log("[regKey=" + this.regKey + "]process over[status=" + this.statusDescr + "]");
                console.log(JSON.stringify(this.logEntity));
                this.finalHandler( {regKey:this.regKey,status:this.statusDescr} );
            },
            callNext: function (nodeKey) {
                console.log("callNext: " + nodeKey);
                var node = this.treeObj[nodeKey];

                if (node != null) {
                    var method = this.methodObj[nodeKey];
                    this.logEntity.push("[start node:" + nodeKey + "][" + Date.now() + "]");
                    this.isWork = true;
                    if (node.needResult != null) {
                        method.call(this, this.treeObj[node.needResult].result);
                    } else {
                        method.call();
                    }
                } else {
                    this.statusDescr = "complete";
                    this.stopProcess();
                }
            },
            addOrderFunObj: function (nodeKey, options) {
                var self = this;
                options = $.extend({}, {
                    judge: function (data) {
                        return true;
                    },
                    success: function (data) {
                        console.log(data);
                    },
                    error: function (data) {
                        console.log(data);
                    }
                }, options);
                var wrapHandler = function (data) {
                    self.logEntity.push("[end nodeKey:" + nodeKey + "][" + Date.now() + "]");
                    self.treeObj[nodeKey].result = data;
                    if (!options.judge(data)) {
                        self.logEntity.push("[interrupt nodeKey:" + nodeKey + "][" + JSON.stringify(data) + "]");
                        self.statusDescr = "interrupt";
                        self.stopProcess();
                    } else {
                        self.currentKey = self.treeObj[nodeKey].nextKey;
                    }
                    self.isWork = false;
                }

                var tempOptions = $.extend({}, options, {
                    success: function (data) {
                        options.success(data);
                        wrapHandler(data);
                    },
                    error: function (data) {
                        options.error(data);
                        wrapHandler(data);
                    }
                })
                self.methodObj[nodeKey] = function () {
                    var finalOptions = tempOptions;
                    var result = null;
                    if (finalOptions.needResult != null) {
                        if (finalOptions.needResult in self.treeObj) {
                            result = self.treeObj[finalOptions.needResult].result
                        }
                        if(typeof finalOptions.checkNeedResult == "function"){
                            if( !finalOptions.checkNeedResult( result )){
                                console.log("checkNeedResult fail" )
                                self.statusDescr = "interrupt";
                                self.stopProcess();
                                return ;
                            }
                        }
                    }
                    if ( typeof  options.beforeQuery == "function") {
                        finalOptions = options.beforeQuery.call(this, finalOptions, result);
                    }
                    $.ajax(finalOptions);
                }
            },
            addProcessTree: function (node) {
                this.treeObj[node.key] = node;
                if (node.root == true) {
                    this.rootKey = node.key;
                    this.currentKey = node.key;
                }
            }
        });
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Carousel.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel',['require','exports','module'],function(require, exports, module) {
        window.Carousel = window.Carousel || {
            version: '1.0'
        };

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Carousel.Action.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel.Action',['require','exports','module'],function(require, exports, module) {
        Carousel.Action = (function(){
            var listGrid = null;
            var insertGrid = null;
            var libraryGrid = null;
            var ruleGrid = null;
            var automationRuleGrid = null;
            var listRun = function(){
                if (!listGrid) {
                    listGrid = new Carousel.Grid($.extend(true, {
                        $grid:$('#list'),
                        type: 0
                    }, {}));
                }
                listGrid.runDayList();
                console.log('Carousel grid runDayList');
            }
            var insertRun = function(){
                if (!insertGrid) {
                    insertGrid = new Carousel.Grid($.extend(true, {
                        $gridType1:$('#listAdd1'),
                        $gridType2:$('#listAdd2'),
                        type: 0
                    }, {}));
                }
                insertGrid.runInsertList();
                console.log('Carousel grid runInsertList');
            }

            var libraryRun =function (){
                if (!libraryGrid) {
                    libraryGrid = new Carousel.Grid($.extend(true, {
                        $grid:$('#list'),
                        type: 0
                    }, {}));
                }
                libraryGrid.runLibrary();
                console.log('Carousel grid runLibrary');
            }

//            var ruleRun =function (){
//                if (!ruleGrid) {
//                    ruleGrid = new Carousel.Grid($.extend(true, {
//                        $grid:$('#list'),
//                        type: 0,
//                        model:"rule"
//                    }, {}));
//                }
//                ruleGrid.runRule();
//                console.log('Carousel grid runRule');
//            }

            var automationRuleRun =function (){
                if (!automationRuleGrid) {
                    automationRuleGrid = new Carousel.AutomationRuleGrid($.extend(true, {
              //      automationRuleGrid = new Carousel.Grid($.extend(true, {
                        $grid:$('#ruleList'),
                        type: 0,
                        model:"automation_rule"
                    }, {}));
                }
                automationRuleGrid.runAutomationRule();
                console.log('Carousel grid runAutomationRule');
            }

            return {
                listRun:listRun,
                insertRun:insertRun,
                libraryRun:libraryRun,
             //   ruleRun:ruleRun,
                automationRuleRun:automationRuleRun
            }
        })();

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.Config.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel.Config',['require','exports','module'],function (require, exports, module) {
        Carousel.Config = $.extend({}, Ancestor.Config, {
            TABLE_COLMODEL_CONFIG: {
                index: {
                    name: "index",
                    index: 'index',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    editable: true,
                    edittype: "text",
                    editrules: {
                        custom: true,
                        custom_func: function (value, colName) {
                            if (value == null) {
                                return [false, ""];
                            }
                            if (!/^[1-9]\d*$/.test(value)) {
                                return [false, "请输入正整数"];
                            }
                            var obj = $("#list").jqGrid("getRowData");
                            if (parseInt(value, 10) > obj.length) {
                                return [false, "长度越界"];
                            }
                            console.log("editrules excute");
                            return [true, ""];
                        }
                    }
                },
                qipuId: {
                    name: "qipuId",
                    index: 'qipuId',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.qipuId(cellvalue, options, rowObject);
                    }
                },
                qipuIdNew: {
                    name: "qipuId",
                    index: 'qipuId',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.qipuIdNew(cellvalue, options, rowObject);
                    }
                },
                displayName: {
                    name: "displayName",
                    index: 'displayName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.wrapColor(rowObject, cellvalue)
                    }
                },
                programName: {
                    name: "programName",
                    index: 'programName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                twProgramName: {
                    name: "twProgramName",
                    index: 'twProgramName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function(cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.twProgramName(cellvalue, options, rowObject);
                    }
                },
                albumId: {//专辑ID
                    name: "albumId",
                    index: 'albumId',
                    title: false,
                    width: 100,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return  Carousel.Util.formatter.albumId(cellvalue, options, rowObject);
                    }
                },
                channelName: {
                    name: "channelName",
                    index: 'channelName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.wrapColor(rowObject, cellvalue)
                    }
                },
                twChannelName: {
                    name: "twChannelName",
                    index: 'twChannelName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.twChannelName(cellvalue, options, rowObject)
                    }
                },

                channelName2: {
                    //所属频道
                    name: "channelName",
                    index: 'channelName',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center"
                },

                globalPublishDate: {
                    name: "globalPublishDate",
                    index: 'globalPublishDate',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.wrapColor(rowObject, cellvalue == null ? "" : cellvalue)
                    }
                },
                duration: {
                    name: "duration",
                    index: 'duration',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        var calculateDuration = ( cellvalue / 1000 >> 0);
                        return Carousel.Util.formatter.wrapColor(rowObject, Carousel.Util.tranDurationFormat(calculateDuration));
                    }
                },
                pagePublishStatus: {
                    name: "pagePublishStatus",
                    index: 'pagePublishStatus',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.wrapColor(rowObject, Carousel.Util.formatter.publishStatus(cellvalue));
                    }
                },
                copyrightEndTime: {
                    name: "copyrightEndTime",
                    index: 'copyrightEndTime',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.wrapColor(rowObject, Carousel.Util.formatter.copyrightEndTime(cellvalue));
                    }
                },
                purchase: {
                    name: "bossStatus",
                    index: 'bossStatus',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    hidden: true,
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.wrapColor(rowObject, Carousel.Util.formatter.purchase(cellvalue));
                    }
                },
                pname: {
                    name: "pname",
                    index: 'pname',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },

                pnameNew: {
                    name: "pname",
                    index: 'pname',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.pnameNew(cellvalue, options, rowObject);
                    }
                },
                referContentType: {
                    name: "referContentType",
                    index: 'referContentType',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.referContentType(cellvalue, options, rowObject);
                    }
                },
                albumName: {
                    name: "albumName",
                    index: 'albumName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                twAlbumName: {
                    name: "twAlbumName",
                    index: 'twAlbumName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function(cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.twProgramName(cellvalue, options, rowObject);
                    }
                },
                startPlayTime: {
                    name: "startPlayTime",
                    index: 'startPlayTime',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                endPlayTime: {
                    name: "endPlayTime",
                    index: 'endPlayTime',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                live: {
                    name: "live",
                    index: 'live',
                    title: false,
                    width: 100,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.live(cellvalue, options, rowObject);
                    }
                },
                type: {
                    name: "type",
                    index: 'type',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.type(cellvalue, options, rowObject);
                    }
                },
                itemTime: {
                    index: 'itemTime',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        var duration = (new Date(rowObject.endPlayTime.replace(/-/g, "/")).getTime() - new Date(rowObject.startPlayTime.replace(/-/g, "/")).getTime()) / 1000;
                        return Carousel.Util.tranDurationFormat(duration);
                    }
                },
                bossStatus: {
                    name: "bossStatus",
                    index: 'bossStatus',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.bossStatus(cellvalue, options, rowObject);
                    }
                },
                updateTime: {
                    name: "updateTime",
                    index: 'updateTime',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                hiddenData_LIST: {
                    name: "hiddenData",
                    index: "hiddenData",
                    title: false,
                    hidden: true,
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.hiddenData_list(cellvalue, options, rowObject);

                    }
                },
                operator: {
                    title: false,
                    width: 260,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.operator(cellvalue, options, rowObject);
                    }
                },

                opUser: {
                    name: "opUser",
                    index: 'opUser',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                sortIndex: {
                    name: "index",
                    index: 'index',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    editable: true,
                    edittype: "text",
                    editrules: {
                        custom: true,
                        custom_func: function (value, colName) {
                            if (!/^[1-9]\d*$/.test(value)) {
                                return [false, "请输入正整数"];
                            }
                            console.log("editrules excute");
                            //Carousel.
                            return [true, ""];
                        }
                    }
                },
                hiddenData_carousel_episode: {
                    name: "hiddenData",
                    index: "hiddenData",
                    title: false,
                    hidden: true,
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.hiddenData_carousel_episode(cellvalue, options, rowObject);
                    }
                },

                showName: {
                    name: "showName",
                    index: 'showName',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.showName(cellvalue, options, rowObject);
                    }
                },
                channelTag: {
                    name: "channelTag",
                    index: 'channelTag',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                publishStatus: {
                    name: "publishStatus",
                    index: 'publishStatus',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.publishStatus(cellvalue);
                    }
                },
                bossStatus_rule: {
                    name: "bossStatus",
                    index: 'bossStatus',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: "center",
                    //(1：免费 2：收费)
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.bossStatus_rule(cellvalue, options, rowObject);
                    }
                },
                startTime: {
                    name: "startTime",
                    index: 'startTime',
                    title: false,
                    width: 160,
                    sortable: false,
                    align: "center"
                },
                endTime: {
                    name: "endTime",
                    index: 'endTime',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.endTime(cellvalue, options, rowObject);
                    }
                },
                type_rule: {
                    name: "type",
                    index: 'type',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.type_rule(cellvalue, options, rowObject);
                    }
                },
                followedStatus: {
                    name: "followedStatus",
                    index: 'followedStatus',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.followedStatus(cellvalue, options, rowObject);
                    }
                },
                followNum: {
                    name: "followNum",
                    index: 'followNum',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center"
                },
                repeatedStatus: {
                    name: "repeatedStatus",
                    index: 'repeatedStatus',
                    title: false,
                    width: 60,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.repeatedStatus(cellvalue, options, rowObject);
                    }
                },
                currentDisplay: {
                    index: 'currentDisplay',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.currentDisplay(cellvalue, options, rowObject);
                    }
                },
                totalNum: {
                    name: "totalNum",
                    index: 'totalNum',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center"
                },
                restDay: {
                    index: 'rest',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.restDay(cellvalue, options, rowObject);
                    }
                },
                operator_rule: {
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.operator_rule(cellvalue, options, rowObject);
                    }
                },
                hiddenData_rule: {
                    name: "hiddenData",
                    index: "hiddenData",
                    title: false,
                    hidden: true,
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.hiddenData_rule(cellvalue, options, rowObject);
                    }
                },
                operator_carousel_episode: {
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (cellvalue, options, rowObject) {
                        return Carousel.Util.formatter.operator_carousel_episode(cellvalue, options, rowObject);
                    }
                },
                createdTime: {
                    name: "createdTime",
                    index: 'createdTime',
                    title: false,
                    width: 120,
                    sortable: false,
                    align: "center"
                },
                log_id: {
                    name: 'id',
                    index: 'id',
                    title: false,
                    sortable: false,
                    hidden: true
                },
                log_addTime: {
                    name: 'addTime',
                    index: 'addTime',
                    sortable: false,
                    title: false,
                    width: 150,
                    align: 'center'
                },
                log_user: {
                    name: 'user',
                    index: 'user',
                    sortable: false,
                    title: false,
                    width: 150
                },
                log_type: {
                    name: 'type',
                    index: 'type',
                    sortable: false,
                    title: false,
                    width: 120,
                    formatter: function (v, o, r) {
                        return Carousel.Util.formatter.log_type(v, o, r);
                    }
                },
                log_descr: {
                    name: "descr",
                    index: 'descr',
                    title: false,
                    width: 450,
                    sortable: false
                },

                advertEnable: {
                    name: 'advertEnable',
                    index: 'advertEnable',
                    sortable: false,
                    title: false,
                    width: 120,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Carousel.Util.formatter.advertEnable(v, o, r);
                    }
                },
                actualNum: {
                    name: "actualNum",
                    index: 'actualNum',
                    title: false,
                    width: 80,
                    align: "center",
                    sortable: false
                },
                status_automation_rule: {
                    name: "status",
                    index: 'status',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Carousel.Util.formatter.status_automation_rule(v, o, r);
                    }
                },
                operator_automation_rule: {
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Carousel.Util.formatter.operator_automation_rule(v, o, r);
                    }
                },
                currentExec: {
                    name: "currentExec",
                    index: 'currentExec',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter: function (v, o, r) {
                        return Carousel.Util.formatter.currentExec(v, o, r);
                    }
                },
                publishStatus_automation_rule:           {
                    name: "publishStatus",
                    index: 'publishStatus',
                    title: false,
                    width: 80,
                    sortable: false,
                    align: "center",
                    formatter:function (v, o, r) {
                        return Carousel.Util.formatter.publishStatus_automation_rule(v, o, r);
                    }
                    //1：未发布 2：已发布)

                }
            },


            TABLE_LIST: {
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                beforeSelectRow: function (rowid, e) {
                    if (JSON.parse($("#" + this.id).getRowData(rowid).hiddenData).lockStatus == 1) {
                        return false;
                    }
                    if (e.target.localName === 'input' || e.target.getAttribute("aria-describedby") === this.id + "_index") {
                        return true;
                    }
                },
                beforeProcessing: function (gdata, status, xhr) {
                    var listData = gdata.data;
                    var filterResult = listData.result;
                    $.ajax({
                        type: "post",
                        url: EpgWeb.urlConfig.yesterdayEndTimeUrl,
                        beforeSend: function (request) {
                            request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                        },
                        dataType: "json",
                        data: {channelId: Carousel.Dao.channelId, newStartTime: new Date((Carousel.Config.dateTime + " 00:00:00").replace(/-/g, "/")).getTime()  },
                        success: function (data) {
                            if (data.code === "A00000") {
                                Carousel.Dao.cfgName.yesterdayEndTime = Carousel.Util.formatDateTimeFormat(new Date(data.data));
                                console.log(" Carousel.memo.yesterdayEndTime:" + Carousel.Dao.cfgName.yesterdayEndTime);
                            }
                            Carousel.Dao.putToCache("originalArr", filterResult);
                            var rest = listData.totalCount % listData.pageSize;
                            listData.totalPages = (listData.totalCount - rest ) / listData.pageSize + (rest == 0 ? 0 : 1);
                            var fillData = {"total": listData.totalPages, "page": listData.pageNo, "records": listData.totalCount, "rows": filterResult};
                            $("#list")[0].addJSONData(fillData);
                            Carousel.Util.showNoResult(fillData.rows.length);
                            Carousel.Util.recordDuration(filterResult);
                            Carousel.Util.setColorTime(filterResult);
                            Carousel.Util.addBreakHint(filterResult);
                            Carousel.Util.fillLineNo();
                            Carousel.Util.checkSelectAble(filterResult);
                        }
                    })
                    return false;
                },
                jsonReader: {
                    id: "id",
                    root: "rows",
                    page: "page",
                    total: "total",
                    records: "records"
                },
                cellEdit: true,
                cellsubmit: 'clientArray',
                afterSaveCell: function (rowid, cellname, value, iRow, iCol) {
                    console.log("afterSaveCell value:" + value);
                    var dataOriginal = Carousel.Dao.getFromCache("originalArr");
                    var targetElement = dataOriginal[value - 1];
                    console.log("id" + rowid + ";aimid" + targetElement.id);
                    Carousel.Util.programIndexMove(rowid, targetElement.id);
                },
                afterEditCell: function (rowid, cellname, value, iRow, iCol) {
                    var inputCell = $("#list").find("input[name=index]");
                    inputCell.focusout(function (event) {
                        setTimeout(function () {
                            var e = jQuery.Event("keydown");
                            e.keyCode = 13;
                            $(event.currentTarget).trigger(e);
                        }, 100)
                    });
                },
                loadComplete: function () {
                    var jqGridTarget = $("#list");
                    var re_records = jqGridTarget.getGridParam('records');
                    Carousel.Util.showNoResult((re_records == 0 || re_records == null) ? 0 : 1);
                },
                beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
                    console.log(" beforeEditCell ");
                    var currentDay = new Date();
                    currentDay.setTime(currentDay.getTime() + 30 * 60 * 1000)
                    var checkTime = Carousel.Util.formatDateTimeFormat(currentDay);
                    var jqGridTarget = $("#list");
                    var element = jqGridTarget.getRowData(rowid);
                    var hiddenData = JSON.parse(element.hiddenData);
                    var checkObj = {};
                    if (hiddenData.lockStatus == 1) {
                        checkObj.msg = Carousel.Config.EditErrorMsg.ERROR_LOCK;
                    } else if (element.live !== "点播") {
                        checkObj.msg = Carousel.Config.EditErrorMsg.ERROR_NOT_SUPPORT;
                    } else if (element.startPlayTime < checkTime) {
                        checkObj.msg = Carousel.Config.EditErrorMsg.ERROR_NOT_ALLOWED;
                    }
                    if (checkObj.msg != null) {
                        EpgWeb.Plugin.showTips({content: checkObj.msg, type: "error" });
                        setTimeout(function () {
                            jqGridTarget.restoreCell(iRow, iCol);
                        }, 50);
                    } else {
                        setTimeout(function () {
                            jqGridTarget.find("#" + rowid).find("td:eq(" + iCol + ")").find("input").select();
                        }, 50);
                    }
                },
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                multiselect: true,
                mtype: "post",
                datatype: "local",
                height: 450,
                rowNum: 500,
                caption: "节目单列表",
                colNames: ["序号", "奇谱ID", "节目名称", "内容类型", "所属专辑", "是否包含广告点", "开始时间", "结束时间", "播放类型", "节目类型", "付费状态", "更新日期", "隐藏数据", "操作"],
                colModel: ["index", "qipuIdNew", "pnameNew", "referContentType", "albumName", "advertEnable", "startPlayTime", "endPlayTime", "live", "type", "bossStatus", "updateTime", "hiddenData_LIST", "operator"],
                pager: "#pager",
                toolbar: [true, "top"]
            },

            TABLE_LIST_ADD_TYPE1: {
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                beforeProcessing: function (data, status, xhr) {
                    var self = this;
                    if (data != null && data.data != null) {
                        Carousel.Util.checkQipuPlatformControl(function (data) {
                            var filterResult = [];
                            $.each(data.result, function (i, element) {
                                if (!element.illegal) {
                                    filterResult.push(element)
                                } else {
                                    console.log("illegal:" + element.qipuId);
                                }
                            })
                            var fillData = {"total": data.totalPages, "page": data.pageNo, "records": data.totalCount, "rows": filterResult};
                            Carousel.Dao.putToCache("gridData1", fillData);
                            $("#listAdd1")[0].addJSONData(fillData);
                            Carousel.Util.showNoResult(fillData.rows.length, "#listAdd1");
                        }, data.data)
                    } else {
                        var msg = "接口url：" + EpgWeb.Constant.thirdUrl_apis_search_area_url + ";<br>" + (data == null ? "请求lego接口失败" : data.msg);
                        SystemDialog.queryAlert(msg);
                        console.log("错误信息:" + JSON.stringify(data));
                    }
                    return false;
                },
                serializeGridData: function (postData) {
                    if (postData.request != null) {
                        var requestData = JSON.parse(postData.request);
                        requestData.params["page.pageNo"] = postData["page.pageNo"];
                        postData.request = JSON.stringify(requestData)
                    }
                    return postData
                },
                jsonReader: {
                    id: "qipuId",
                    root: "rows",
                    page: "page",
                    total: "total",
                    records: "records"
                },
                multiselect: true,
                mtype: "post",
                datatype: "local",
                width: 1300,
                height: 450,
                rowNum: 30,
                caption: "点播列表",
                colNames: ["奇谱ID", "节目名称", "专辑ID", "频道", "发行时间", "时长", "发布状态", "版权到期时间", "付费"],
                colModel: ["qipuId", "displayName", "albumId", "channelName", "globalPublishDate", "duration", "pagePublishStatus", "copyrightEndTime", "purchase"],
                pager: "#pagerAdd1"
            },
            TABLE_LIST_ADD_TYPE2: {
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                jsonReader: {
                    id: "qipuId"
                },
                multiselect: true,
                loadComplete: function () {
                    var jqGridTarget = $("#listAdd2");
                    var re_records = jqGridTarget.getGridParam('records');
                    var parentElement = jqGridTarget.parent()
                    var dataLength = re_records == 0 || re_records == null ? 0 : re_records;
                    Carousel.Util.showNoResult(dataLength, "#listAdd2");
                },
                mtype: "post",
                datatype: "local",
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                width: 860,
                height: 450,
                rowNum: 50,
                caption: "直播列表",
                colNames: ["奇谱ID", "节目名称", "开始时间", "结束时间", "时长", "节目类型", "付费", "所属频道"],
                colModel: ["qipuId", "pname", "startPlayTime", "endPlayTime", "itemTime", "type", "bossStatus", "channelName2"],
                pager: "#pagerAdd2"
            },

            TABLE_LIBRARY: {
                url: EpgWeb.urlConfig.carouselEpisodeListUrl,
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                beforeSelectRow: function (rowid, e) {
                    if (Carousel.Config.IS_RULE_RUNNING) {
                        return false;
                    }
                    if (e.target.localName === 'input' || e.target.getAttribute("aria-describedby") === this.id + "_index") {
                        return true;
                    }
                },
                cellEdit: true,
                cellsubmit: 'clientArray',
                afterSaveCell: function (rowid, cellname, value, iRow, iCol) {
                    console.log("afterSaveCell value:" + value);
                    var params = $("#list").jqGrid("getGridParam");
                    var selIdx = (params.page - 1) * params.rowNum + iRow;
                    if (selIdx > value) {
                        value--;
                    }
                    console.log("id" + rowid + "; aimIdx:" + value);
                    Carousel.Util.episodeIndexMove(rowid, value);
                    // Carousel.Operation.indexMove(rowid, targetElementId);
                },
                //   cellurl: Carousel.urlConfig.programIndexMoveUrl,
                afterEditCell: function (rowid, cellname, value, iRow, iCol) {
                    var inputCell = $("#" + this.id).find("input[name=index]");
                    inputCell.focusout(function (event) {
                        setTimeout(function () {
                            var e = jQuery.Event("keydown");
                            e.keyCode = 13;
                            $(event.currentTarget).trigger(e);
                        }, 100)
                    });
                },
                loadComplete: function () {
                    var jqGridTarget = $("#list");
                    var re_records = jqGridTarget.getGridParam('records');
                    Carousel.Util.showNoResult((re_records == 0 || re_records == null) ? 0 : 1);
                    Carousel.Util.toggleTwColumns();
                    Carousel.Util.fillLineNo();
                },
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                multiselect: true,
                mtype: "get",
                datatype: "local",
                width: 1300,
                height: 450,
                rowNum: 30,
                caption: "循环节目列表",
                //
                colNames: ["序号", "节目奇谱ID", "节目名称", "专辑", "频道","节目名称", "专辑", "频道", "操作", "操作人", "操作时间", "发行时间", "时长", "发布状态", "版权到期时间", "付费", "隐藏数据"],
                colModel: ["sortIndex", "qipuId", "programName", "albumName", "channelName", "twProgramName", "twAlbumName", "twChannelName", "operator_carousel_episode", "opUser", "createdTime", "globalPublishDate", "duration", "pagePublishStatus", "copyrightEndTime", "purchase", "hiddenData_carousel_episode"],
                pager: "#pager"
            },
            TABLE_RUN: {
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                loadComplete: function () {
                    var dataOriginl = $("#list").jqGrid("getRowData");
                    if (dataOriginl == null || dataOriginl.length == 0) {
                        return;
                    }
                    Carousel.Util.checkSelectAble(dataOriginl);
                },
                beforeSelectRow: function (rowid, e) {
                    if (e.target.localName === 'input') {
                        return true;
                    }
                },
                multiselect: true,
                mtype: "post",
                datatype: "json",
                width: 1380,
                height: 450,
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                rowNum: 20,
                caption: "规则列表",
                colNames: ["奇谱ID", "显示名称", "频道", "状态", "付费", "开始时间", "结束时间", "类型", "跟播", "连播", "循环播放", "当前", "总集数", "到期", "操作", "隐藏数据"],
                colModel: ["qipuId", "showName", "channelTag", "publishStatus", "bossStatus_rule", "startTime", "endTime", "type_rule", "followedStatus", "followNum", "repeatedStatus", "currentDisplay", "totalNum", "restDay", "operator_rule", "hiddenData_rule"],
                pager: "#pager"
            },
            TABLE_AUTOMATION_RULE: {
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                beforeSelectRow: function (rowid, e) {
                    if (JSON.parse($("#ruleList").getRowData(rowid).hiddenData).status == 1) {
                        return false;
                    }
                    if (e.target.localName === 'input' || e.target.getAttribute("aria-describedby") === "ruleList_index") {
                        return true;
                    }
                },

                cellEdit: true,
                cellsubmit: 'clientArray',
                afterSaveCell: function (rowid, cellname, value, iRow, iCol) {
                    console.log("afterSaveCell value:" + value);
                    value--;
                    console.log("id" + rowid + "; aimIdx:" + value);
                    //   Carousel.Operation.indexMove(rowid, targetElementId);
                },
                //   cellurl: Carousel.urlConfig.programIndexMoveUrl,
                afterEditCell: function (rowid, cellname, value, iRow, iCol) {
                    var inputCell = $("#ruleList").find("input[name=index]");
                    inputCell.focusout(function (event) {
                        setTimeout(function () {
                            var e = jQuery.Event("keydown");
                            e.keyCode = 13;
                            $(event.currentTarget).trigger(e);
                        }, 100)
                    });
                },
                loadComplete: function () {
                    var jqGridTarget = $("#ruleList");
                    var re_records = jqGridTarget.getGridParam('records');
                    Carousel.Util.showNoResult((re_records == 0 || re_records == null) ? 0 : 1, "#ruleList");
                    Carousel.Util.fillLineNo("#ruleList");
                    Carousel.Util.notifyChangeBtnStatus("#ruleList");
                },
                multiselect: true,
                mtype: "get",
                datatype: "local",
                width: 1380,
                height: 450,
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                rowNum: 20,
                caption: "规则列表",
                colNames: ["序号", "奇谱ID", "显示名称", "频道", "发布状态", "付费", "设定总集数", "实际总集数", "操作", "规则状态", "最近执行", "隐藏数据"],
                colModel: ["sortIndex", "qipuId", "showName", "channelTag", "publishStatus", "bossStatus_rule", "totalNum", "actualNum", "operator_automation_rule" , "status_automation_rule", "currentExec", "hiddenData_carousel_episode"],
                pager: "#pagerAutoRule"
            },
            TABLE_LOG: {
                url: EpgWeb.urlConfig.programLog,
                loadBeforeSend: function (xhr, settings) {
                    var auth = Ancestor.Util.getAuth("/program/loglist");
                    xhr.setRequestHeader('Sign', auth.sign);
                    xhr.setRequestHeader("Time", auth.clientTime);
                    xhr.setRequestHeader("From", auth.from);
                    return true;
                },
                multiselect: false,
                loadtext: '加载中...',
                loadui: 'block',
                rowNum: 50,
                mtype: "post",
                datatype: "local",
                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                colNames: ["ID", "操作时间", "人员", "动作", "备注"],
                colModel: ['log_id', "log_addTime", "log_user" , "log_type" , "log_descr"],
                pager: "#log_pager"
            },

            ErrorMsg: {
                PPS_CLIENT_MSG: "该专辑在PPS端没有上线，但会在PPS平台播出，是否确认添加？",
                PPS_REGION_MSG: "该专辑在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？",
                QIYI_CLIENT_MSG: "该专辑在QIYI端没有上线，但会在QIYI平台播出，是否确认添加？",
                QIYI_REGION_MSG: "该专辑在QIYI端有地域播控，但会在QIYI平台全地域播出，是否确认添加？"

            },
            Hint: {
                QUERY_ADD: "是否确认添加？",
                NOT_CAROUSEL: "当前频道不是轮播台",
                NO_AUTH: "很抱歉，您没有删除的权限!",
                QUERY_DEL: "确认删除？",
                PPS_CLIENT_HINT: "在PPS端没有上线，但会在PPS平台播出",
                PPS_REGION_HINT: "在PPS端有地域播控，但会在PPS平台全地域播出",
                QIYI_CLIENT_HINT: "在IQIYI端没有上线，但会在IQIYI平台播出",
                QIYI_REGION_HINT: "在IQIYI端有地域播控，但会在IQIYI平台全地域播出",
                STOP_RULE_HINT: "是否确认停止运行自动化规则？停止后已生成的节目单将会在新规则重新运行时被清空，并按新规则重新生成节目单。"
            },
            EditErrorMsg: {
                ERROR_LOCK: "锁定的节目无法排序",
                ERROR_NOT_SUPPORT: "直播节目不支持索引调整",
                ERROR_NOT_ALLOWED: "节目已播放完毕或正在播放中，不可修改。"
            },
            Header: {
                daojuSuggest: ["道具渠道号", "道具渠道名称", "创建时间", "创建人"],
                voteSuggest: ["投票ID", "投票名称", "创建时间"],
                puyuSuggest: ["条形码", "片名", "出品方", "发行时间", "主演 /演唱者", "导演", "版权方", "合同编号", "授权起止时间"],
                albumSuggest: ["奇谱ID", "显示名称", "频道", "版权到期时间", "是否付费", "发布状态"],
                qitanSuggest: ["评论ID", "评论名称", "创建时间"],
                actorSuggest: ["人物ID", "名称", "别名", "性别", "人物类型", "审核状态"],
                playbackSuggest: ["节目Id", "节目显示名称", "频道", "发行时间", "是否付费", "发布状态"]
            },
            ChangeStatus: {
                STATUS_ILLEGAL: -2,
                STATUS_DELETE: -1,
                STATUS_IDLE: 0,
                STATUS_RUN: 1,
                STATUS_PROGRAM_IDLE: 3,
                STATUS_PROGRAM_RUN: 2
            },
            durationMap: null,
            dateTime: null,
            saveIds: null,
            sequeueArr: [],
            invalidArr: null,
            timerId: -1,
            lockFlag: false,
            ruleSelectElement: null,
            IS_RULE_RUNNING: true,
            BIND_BATCH_ADD_MODEL: null,
            AUTH_LOG_DETAIL: false
        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.Dao.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel.Dao',['require','exports','module'],function (require, exports, module) {

        Carousel.Dao = $.extend({}, EpgWeb.Dao, {
            cache: {},
            getChannel: function () {
                return this.getDataByName(this.cfgName.getChannel).data;
            },

            liveProgramType: function () {
                return this.getDataByName(this.cfgName.liveProgramType);
            },

            getPrograms: function () {
                return this.getDataByName(this.cfgName.programList).data;
            },
            channelList: function () {
                return this.getDataByName(this.cfgName.channelList);
            },

            getPlatformType: function () {
                return this.getDataByName(this.cfgName.PlayPlatform)
            },

            getPlatformRefer: function () {
                return this.getDataByName(this.cfgName.PlatformRefer)
            },

            getPlatSettings: function () {
                return this.getDataByName(this.cfgName.platSettings)
            },

            getContentType: function () {
                return this.getDataByName(this.cfgName.ContentType);
            },
            logType: function () {
                return this.getDataByName(this.cfgName.LogType);
            },
//            adDuration:function(){
//                return this.getDataByName(this.cfgName.Ad_duration);
//            },
            getFromCache: function (dataKey) {
                return this.cache[dataKey]
            },

            putToCache: function (dataKey, data) {
                this.cache[dataKey] = data
            },

            deleteProgramData: function (data, callback) {
                var self = this;
                self.doAuthData({
                    url: '/epg/carousel_program_delete.html',
                    doError: function () {
                        EpgWeb.Plugin.showTips({content: Carousel.Config.Hint.NO_AUTH, type: "error"})
                    },
                    doSuccess: function () {
                        SystemDialog.queryConfirm(Carousel.Config.Hint.QUERY_DEL, function (flag) {
                            if (flag === true) {
                                self.sendAjax(EpgWeb.urlConfig.programDel, 'post', data, callback, '/program/delete')
                            }
                        })
                    }
                })
            },
            programBatchDel: function (data, callback) {
                var self = this;
                self.doAuthData({
                    url: '/epg/carousel_program_delete.html',
                    doError: function () {
                        EpgWeb.Plugin.showTips({content: Carousel.Config.Hint.NO_AUTH, type: "error"})
                    },
                    doSuccess: function () {
                        SystemDialog.queryConfirm(Carousel.Config.Hint.QUERY_DEL, function (flag) {
                            if (flag === true) {
                                self.sendAjax(EpgWeb.urlConfig.programBatchDelUrl, 'post', data, callback, '/program/batchDel')
                            }
                        })
                    }
                })
            },
            programMove: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.programMoveUrl, 'post', data, callback, '/program/move')
            },
            programToggleLock: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.programToggleLockUrl, 'post', data, callback, '/program/toggleLock')
            },
            programIndexMove: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.programIndexMoveUrl, 'post', data, callback, '/program/indexMove')
            },
            gridSort: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.programDaySortUrl, 'post', data, callback, '/program/daySort')
            },
            batchAdd: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.programBatchAddUrl, 'post', data, callback, '/program/batchAdd')
            },
            getProgramList: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.programList, 'post', data, callback, '/program/list')
            },
            episodeBatchAdd: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.carouselEpisodeBatchAddUrl, 'post', data, callback, '/carousel/carouselEpisode/batchAdd')
            },
            episodeIndexMove:function(data, callback){
                this.sendAjax(EpgWeb.urlConfig.carouselEpisodeIndexMoveByIndexUrl, 'post', data, callback, '/carousel/carouselEpisode/indexMove/byIndex')
            },
            getCarouselEpisodeList: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.carouselEpisodeListUrl, 'get', data, callback, '/carousel/carouselEpisode/list')
            },
            notifyRuleChangeStatus: function (data, callback) {
                this.sendAjax(EpgWeb.urlConfig.automationChangeStatusUrl, 'get', data, callback, '/carousel/automation/changeStatus')
            },
            postModifyAdvert:function(data,callback){
                this.sendAjax(EpgWeb.urlConfig.advertModifyUrl, 'post', data, callback, '/advert/modify')
            },
            episodeBatchDel: function (data, callback) {
                var self = this;
                self.doAuthData({
                    url: '/epg/carousel_program_delete.html',
                    doError: function () {
                        EpgWeb.Plugin.showTips({content: Carousel.Config.Hint.NO_AUTH, type: "error"})
                    },
                    doSuccess: function () {
                        SystemDialog.queryConfirm(Carousel.Config.Hint.QUERY_DEL, function (flag) {
                            if (flag === true) {
                                self.sendAjax(EpgWeb.urlConfig.carouselEpisodeBatchDelUrl, 'post', data, callback, '/carousel/carouselEpisode/batchDel')
                            }
                        })
                    }
                })
            },
            automationList:function(data, callback) {
                this.sendAjax(EpgWeb.urlConfig.automationListUrl, 'get', data, callback, '/carousel/automations')
            },
            delAutomationRule:function(data, callback){
                var self = this;
                self.doAuthData({
                    url: '/epg/carousel_program_delete.html',
                    doError: function () {
                        EpgWeb.Plugin.showTips({content: Carousel.Config.Hint.NO_AUTH, type: "error"})
                    },
                    doSuccess: function () {
                        SystemDialog.queryConfirm(Carousel.Config.Hint.QUERY_DEL, function (flag) {
                            if (flag === true) {
                                self.sendAjax(EpgWeb.urlConfig.automationDelUrl, 'post', data, callback, '/carousel/automation/del')
                            }
                        })
                    }
                })
            },
            changeStatusAutomationRule:function(data, callback){
                this.sendAjax(EpgWeb.urlConfig.automationChangeStatusUrl, 'get', data, callback, '/carousel/automation/changeStatus')
            }

        })
        Carousel.Dao.cfgName = $.extend({}, EpgWeb.Dao.cfgName, {
            enumName: "programTypeData",
            listName: "mockData",
            fatherId: 0,
            ContentType: "ContentType",
            getChannelList: "getChannelList",
            getProgramList: "programList",
            channelList: "channelList",
            platSettings: "platSettings",
            PlayPlatform: "PlayPlatform",
            PlatformRefer: "PlatformRefer",
            yesterdayEndTime: 0,
       //     Ad_duration:"ad_duration",
            ad_selected:0
        });
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel.Util',['require','exports','module'],function (require, exports, module) {
        Carousel.Util = $.extend(true, {}, EpgWeb.Util, {
            formatter: {
                qipuId: function (cellvalue, options, rowObject) {
                    var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(rowObject.qipuId);
                    return "<a target='_blank' href='" + plusUrl + "' >" + rowObject.qipuId + "</a>";
                },
                albumId: function (cellvalue, options, rowObject) {
                    if (cellvalue > 0) {
                        var plusUrl = "http://lego.iqiyi.com/apis/search/search-area?filter_EQL_entityId=" + cellvalue + "&t=1";
                        return "<a target='_blank' href='" + plusUrl + "' >" + cellvalue + "</a>";
                    } else {
                        return "";
                    }
                },
                wrapColor: function (rowObject, value) {
                    if (rowObject.hintMsgObj == null) {
                        console.log("rowObject.hintMsgObj is null" + rowObject.qipuId)
                        return value;
                    }
                    if (rowObject.hintMsgObj.missPPSClient || rowObject.hintMsgObj.missQIYIClient) {
                        return  '<span style="color:red;">' + value + '</span>';
                    } else if (rowObject.hintMsgObj.missPPSRegion || rowObject.hintMsgObj.missQIYIRegion) {
                        return  '<span style="color:#ffa800;">' + value + '</span>';
                    }
                    return value
                },
                qipuIdNew: function (cellvalue, options, rowObject) {
                    var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(cellvalue);
                    var colorPart = $("<em>&nbsp;&nbsp;</em>");
                    var currentClient = EpgWeb.Util.formatDateTimeFormat(new Date());
                    if (currentClient >= rowObject.startPlayTime && currentClient <= rowObject.endPlayTime) {
                        colorPart.addClass("current");
                    } else {
                        if (rowObject.startPlayTime.substr(11) >= "12:00:00") {
                            colorPart.addClass("afternoon");
                        } else {
                            colorPart.addClass("morning");
                        }
                    }
                    var cellEnd = cellvalue < 1 ? cellvalue : "<a target='_blank' href='" + plusUrl + "'>" + cellvalue + "</a>"
                    return  colorPart.prop("outerHTML") + cellEnd;
                },
                pnameNew: function (cellvalue, options, rowObject) {
                    var retValue = cellvalue;
                    if (rowObject.pageUrl != null) {
                        retValue = "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>";
                    }
                    if (rowObject.qipuId == 0 && rowObject.live == 1 && retValue.indexOf("delete") != -1) {
                        retValue = "<span style='color: red'>" + retValue + "</span>"
                    }
                    return retValue;
                },
                publishStatus: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    checkValue = checkValue + "";
                    switch (checkValue) {
                        case "0":
                            return "未发布";
                        case "1":
                            return "已发布";
                        case "2":
                            return "页面下线";
                        case "3":
                            return "页面备用"
                        default:
                            return checkValue + "";
                    }
                },

                bossStatus_rule: function (cellvalue, options, rowObject) {
                    if (rowObject.qipuId % 100 == 2) {
                        return "";
                    }
                    if (cellvalue == 1) {
                        return "免费";
                    } else if (cellvalue == 2) {
                        return  "收费";
                    }
                },
                copyrightEndTime: function (checkValue) {
                    if (checkValue == null) {
                        return "";
                    }
                    if (typeof( checkValue ) == "string") {
                        return checkValue;
                    }
                    if (checkValue <= 0) {
                        return "---";
                    } else {
                        var date = new Date();
                        date.setTime(parseInt(checkValue))
                        return  Carousel.Util.formatDateTimeFormat(date);
                    }
                },
                purchase: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    switch (checkValue) {
                        case 0:
                        case -100:
                            return "免费";
                        case 1:
                        case 2:
                            return "收费";
                        default:
                            return checkValue + ""
                    }
                },
                referContentType: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return ""
                    }
                    var response = Carousel.Dao.getContentType();
                    var ret = cellvalue;
                    $.each(response.data, function (index, element) {
                        if (cellvalue == element.val) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                },
                playStatus: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return "Not exist ";
                    }
                    switch (cellvalue) {
                        case -1:
                            return "未设定";
                        case 0:
                            return "未开始";
                        case 1:
                            return "直播中";
                        case 2:
                            return "回看中";
                        case 3:
                            return "回看结束";
                        default :
                            return "Not exist value:" + cellvalue;
                    }
                    return cellvalue;
                },
                bossStatus: function (cellvalue, options, rowObject) {
                    var enumValue = "";
                    switch (cellvalue) {
                        case "FREE":
                            enumValue = "免费";
                            break;
                        case "PAIED_NOT_AVAILABLE":
                            enumValue = "付费未划价";
                            break;
                        case "PAIED_AVAILABLE":
                            enumValue = "付费已划价";
                            break;
                        default:
                            break;
                    }
                    return enumValue;
                },
                type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Carousel.Dao.liveProgramType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret
                },
                live: function (cellvalue, options, rowObject) {
                    if (cellvalue == 0) {
                        return "未设置"
                    } else if (cellvalue == 1) {
                        return "点播"
                    } else if (cellvalue == 2) {
                        return "直播"
                    }
                    return "";
                },
                hiddenData_list: function (cellvalue, options, rowObject) {
                    var data = {};
                    if (typeof rowObject.lockStatus == 'undefined') {
                        rowObject.lockStatus = 0;
                    }
                    data.lockStatus = rowObject.lockStatus;
                    return JSON.stringify(data);
                },
                hiddenData_carousel_episode: function (cellvalue, options, rowObject) {
                    var data = {};
                    data.id = rowObject.id;
                    data.qipuId = rowObject.qipuId;
                    data.fatherId = rowObject.fatherId;
                    data.currentExec = rowObject.currentExec;
                    data.status = rowObject.status;
                    return JSON.stringify(data);
                },
                operator: function (cellvalue, options, rowObject) {
                    var checkDate = new Date();
                    checkDate.setTime(checkDate.getTime() + 30 * 1000 * 60);
                    var checkTime = EpgWeb.Util.formatDateTimeFormat(checkDate);
                    var retOperation = [];
                    if (checkTime > rowObject.startPlayTime) {
                        retOperation.push("<a class='disabled'>编目</a>");
                        retOperation.push(Carousel.Util.getBroadcastControl(rowObject));
                        retOperation.push("<a class='disabled'>广告点</a>");
                        retOperation.push("<a class='disabled'>删除</a>");
                        if (rowObject.live != 2) {
                            retOperation.push("<a class='disabled'>上移</a>");
                            retOperation.push("<a class='disabled'>下移</a>");
                            if (rowObject.lockStatus == 1) {
                                retOperation.push("<a class='disabled'>解锁</a>");
                            } else {
                                retOperation.push("<a class='disabled'>锁定</a>");
                            }
                        }
                    } else {
                        retOperation.push("<a href='javascript:;' onclick='Carousel.Util.jumpListToEdit(" + rowObject.id + "," + rowObject.fatherId + ")'>编目</a>")
                        retOperation.push(Carousel.Util.getBroadcastControl(rowObject));
                        retOperation.push("<a href='javascript:;' onclick='Carousel.Util.modifyAdvert(" + rowObject.id + "," + rowObject.advertEnable + ")'>广告点</a>");
                        retOperation.push("<a href='javascript:;' onclick='Carousel.Util.delProgram(" + rowObject.id + ")'>删除</a>");
                        if (rowObject.live != 2) {
                            if (rowObject.lockStatus == 1) {
                                retOperation.push("<a class='disabled'>上移</a>");
                                retOperation.push("<a class='disabled'>下移</a>");
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programToggleLock(" + rowObject.id + "," + rowObject.fatherId + ", 0)'>解锁</a>");
                            } else {
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programMoveUp(" + rowObject.id + "," + rowObject.fatherId + ")'>上移</a>");
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programMoveDown(" + rowObject.id + "," + rowObject.fatherId + ")'>下移</a>");
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programToggleLock(" + rowObject.id + "," + rowObject.fatherId + ", 1)'>锁定</a>");
                            }
                        }
                    }
                    retOperation.push("<a href='javascript:;' onclick='Carousel.Util.openHistory(" + rowObject.id + ")'>详细</a>");
                    return retOperation.join("&nbsp;");
                },
//                advert_operator: function (cellvalue, options, rowObject) {
//                    var retOperation = "";
//                    retOperation += "<a href='javascript:;' onclick='Carousel.Util.modifyAdvert(" + rowObject.id + ")'>广告点</a>";
//                    retOperation += "<a href='javascript:;' onclick='Carousel.Util.moveAdvert(" + rowObject.id + ",-1)'>上移</a>  ";
//                    retOperation += "<a href='javascript:;' onclick='Carousel.Util.moveAdvert(" + rowObject.id + ",1)'>下移</a>  ";
//                    return retOperation
//                },
                showName: function (cellvalue, options, rowObject) {
                    if (rowObject.pageUrl != null && rowObject.pageUrl.length > 0) {
                        return "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>"
                    }
                    return cellvalue;
                },
                endTime: function (cellvalue, options, rowObject) {
                    if (rowObject.repeatedStatus == 1) {
                        return "------";
                    }
                    return cellvalue.substr(0, 10);
                },
                type_rule: function (cellvalue, options, rowObject) {
                    if (rowObject.qipuId % 100 == 1) {
                        return "专辑"
                    } else if (rowObject.qipuId % 100 == 2) {
                        return "播单"
                    }
                },
                followedStatus: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "是";
                    } else if (cellvalue == 2) {
                        return "否";
                    }
                },
                repeatedStatus: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "是";
                    } else if (cellvalue == 2) {
                        return "否";
                    }
                },
                currentDisplay: function (cellvalue, options, rowObject) {
                    var clientTime = new Date(rowObject.startTime.replace(/-/g, "/"));
                    var serverTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                    this.setZeroTime(clientTime);
                    this.setZeroTime(serverTime);
                    if (rowObject.totalNum == 0 || serverTime.getTime() < clientTime.getTime()) {
                        return "";
                    }
                    var minusDay = ( serverTime.getTime() - clientTime.getTime()) / 86400000;
                    var startRuleNum = minusDay * rowObject.followNum + rowObject.startNum;
                    var repeatFlag = rowObject.repeatedStatus == 1 && rowObject.totalNum == rowObject.actualNum
                    if (repeatFlag) {
                        while (startRuleNum > rowObject.totalNum) {
                            startRuleNum -= rowObject.totalNum;
                        }
                    }
                    if (startRuleNum > rowObject.totalNum) {
                        return ""
                    }
                    var retArr = [];
                    for (var i = 0; i < rowObject.followNum; i++) {
                        if (startRuleNum + i > rowObject.totalNum) {
                            if (repeatFlag) {
                                startRuleNum -= rowObject.totalNum;
                            } else {
                                break;
                            }
                        }
                        retArr.push(startRuleNum + i);
                    }
                    return retArr.join(",");
                },
                restDay: function (cellvalue, options, rowObject) {
                    if (rowObject.repeatedStatus == 1) {
                        return "------";
                    }
                    var checkTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                    var clientTime = new Date(rowObject.endTime.replace(/-/g, "/"));
                    this.setZeroTime(checkTime);
                    this.setZeroTime(clientTime);
                    var minusDay = (clientTime.getTime() - checkTime.getTime() ) / 86400000 + 1;
                    if (minusDay <= 0) {
                        return "结束";
                    } else if (minusDay < 4) {
                        return "<span style='color: red'>" + minusDay + "天</span>"
                    } else {
                        return minusDay + "天"
                    }
                },
                hiddenData_rule: function (cellvalue, options, rowObject) {
                    var expired = 0;
                    if (rowObject.repeatedStatus != 1) {
                        var checkTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                        var clientTime = new Date(rowObject.endTime.replace(/-/g, "/"));
                        this.setZeroTime(checkTime);
                        this.setZeroTime(clientTime);
                        var minusDay = (clientTime.getTime() - checkTime.getTime() ) / 86400000 + 1;
                        if (minusDay <= 0) {
                            expired = 1;
                        }
                    }
                    var data = {};
                    data.id = rowObject.id;
                    data.fatherId = rowObject.fatherId;
                    data.expired = expired;
                    return JSON.stringify(data);
                },
                operator_rule: function (cellvalue, options, rowObject) {
                    return "";
                    //  return "<a href='javascript:;' onclick='Carousel.Util.delAutomationRule(" + rowObject.id + "," + rowObject.fatherId + ")'>删除</a>  ";
                },
                operator_carousel_episode: function (cellvalue, options, rowObject) {
                    if (Carousel.Config.IS_RULE_RUNNING) {
                        return "<a class='disabled'>删除</a> ";
                    }
                    return "<a href='javascript:;' onclick='Carousel.Util.episodeBatchDel(" + rowObject.id + "," + rowObject.fatherId + ")'>删除</a>  ";
                },
                log_type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Carousel.Dao.logType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                },
                advertDuration: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return "";
                    } else if (cellvalue == 0) {
                        return "无";
                    } else {
                        var ret = Carousel.Util.formatDateTimeFormat(new Date(new Date(rowObject.startPlayTime.replace(/-/g, "/")).getTime() - cellvalue * 1000)) + "(" + cellvalue + "秒)"
                        return ret;

                    }
                },
                advertEnable: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return "";
                    } else if (cellvalue == 1) {
                        return "有";
                    } else {
                        return "无";
                    }
                },
                currentExec: function (cellvalue, options, rowObject) {
                    if (cellvalue == 0) {
                        return "否";
                    } else if (cellvalue == 1) {
                        return "是";
                    }
                },
                operator_automation_rule: function (cellvalue, options, rowObject) {
                    if (rowObject.status == 1) {
                        return "<a class='disabled'>删除</a>";
                    }
                    return "<a href='javascript:;' onclick='Carousel.Util.delAutomationRule(" + rowObject.id + "," + rowObject.fatherId + ")'>删除</a>  ";
                },
                status_automation_rule: function (cellvalue, options, rowObject) {
                    switch (cellvalue) {
                        case 1:
                            return "启动";
                        case 0:
                            return "未启动";
                        case -1:
                            return "删除";
                        default :
                            return "unknown value:" + cellvalue;
                    }
                },
                publishStatus_automation_rule: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "未发布";
                    } else if (cellvalue == 2) {
                        return  "已发布";
                    } else {
                        return "未知数值：" + cellvalue;
                    }
                },
                twProgramName: function(cellvalue, options, rowObject) {
                   if(cellvalue == '') {
                       return rowObject.programName;
                   } else {
                       return '' + cellvalue;
                   }
                },

                twChannelName: function(cellvalue, options, rowObject) {
                    var val = null;

                    if(cellvalue == '') {
                        val = rowObject.channelName;
                    } else {
                        val = cellvalue;
                    }

                    return Carousel.Util.formatter.wrapColor(rowObject, val);

                },

                twAlbumName: function(cellvalue, options, rowObject) {
                    if(cellvalue == '') {
                        return rowObject.albumName;
                    } else {
                        return '' + cellvalue;
                    }
                },
            },
            episodeBatchDel: function (entityId, fatherId) {
                Carousel.Dao.episodeBatchDel({ids: "[" + entityId + "]", channelId: fatherId}, function (data) {
                    if (data != null && data.msg != null) {
                        SystemDialog.queryAlert(data.msg);
                    } else {
                        console.log("callbackHandler no return data");
                    }
                    $("#list").trigger("reloadGrid")
                });
            },


            getBroadcastControl: function (rowObj) {
                var hasStream = null != rowObj.channelHasStream && rowObj.channelHasStream == 1;
                if (hasStream) {
                    return "<a href='javascript:;' onclick='Carousel.Util.jumpToBroadcast(" + rowObj.id + "," + rowObj.fatherId + ")'>播控中心</a>";
                } else {
                    return "<a class='disabled'>播控中心</a>";
                }
            },
            jumpToBroadcast: function (entityId, fatherId) {
                var openUrl = "broadcast_manager_episode.html?programId=" + entityId + "&id=" + fatherId;
                window.open(openUrl);
            },
            jumpListToEdit: function (entityId, fatherId) {
                var openUrl = "program_edit.html?id=" + entityId + "&from=carousel&fatherId=" + fatherId;
                window.open(openUrl);
            },
            decodePlayPlatform: function (elementChild) {
                var locationControl = null;
                var platformObject = {platName: null, locationArr: []}
                platformObject.platName = elementChild["play_platform"];
                platformObject.status = 'online';
                if (elementChild["default_control"] != null) {
                    if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                        platformObject.status = "offline";
                    }
                }
                if ($.isArray(elementChild["region_control"])) {
                    $.each(elementChild["region_control"], function (indexRegion, regionElement) {
                        if ($.isArray(regionElement["location"])) {
                            $.each(regionElement["location"], function (j, child) {
                                if (child.hasOwnProperty("province_id")) {
                                    if (child["province_id"] != 95 && child["province_id"] != 148 && child["province_id"] != 228) {
                                        locationControl = regionElement["location_control"];
                                        if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                            platformObject.locationArr.push(child["province_id"]);
                                            console.log("break regionElement location");
                                        }
                                    }
                                }
                            })
                        }
                    })
                }
                return platformObject;
            },
            template: {
                albumSuggest: function (itemArr) {
                    return   '<div class="contract-item" >' +
                        '<span class="contract-width100" style="word-break:break-all">' + itemArr[0] + '</span>' +
                        '<span class="contract-width150" style="word-break:break-all">' + itemArr[1] + '</span>' +
                        '<span class="contract-width60" style="word-break:break-all">' + itemArr[2] + '</span>' +
                        '<span class="contract-width120" style="word-break:break-all">' + itemArr[3] + '</span>' +
                        '<span class="contract-width80" style="word-break:break-all">' + itemArr[4] + '</span>' +
                        '<span class="contract-width80" style="word-break:break-all">' + itemArr[5] + '</span></div>'
                }
            },
            WeekManager: null,
            openNewHtml: function (url) {
                var el = document.createElement("a");
                document.body.appendChild(el);
                el.href = url;
                el.target = '_blank';
                el.click();
                document.body.removeChild(el);
            },
            reloadHandler: function (data, tableName) {
                if (data != null) {
                    EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                    if (data.code == "A00000") {
                        tableName = tableName == null ? "#list" : tableName;
                        $(tableName).trigger("reloadGrid")
                    }
                } else {
                    console.log("callbackHandler no return data");
                }
            },
            delProgram: function (entityId) {
                Carousel.Dao.deleteProgramData({id: entityId }, function (data) {
                    Carousel.Util.reloadHandler(data);
                })
            },

            programMoveUp: function (entityId, fatherId) {
                var sendData = {fatherId: fatherId, id: entityId, flag: 1, operationDay: Carousel.Config.dateTime};
                Carousel.Dao.programMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                });
            },
            programIndexMove: function (entityId, targetId) {
                var sendData = {id: entityId, aimId: targetId, dateTime: Carousel.Config.dateTime, channelId: Carousel.Dao.channelId};
                Carousel.Dao.programIndexMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                })
            },

            programMoveDown: function (entityId, fatherId) {
                var sendData = {fatherId: fatherId, id: entityId, flag: 2, operationDay: Carousel.Config.dateTime};
                Carousel.Dao.programMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                });
            },
            programToggleLock: function (entityId, fatherId, lockType) {
                var sendData = {fatherId: fatherId, id: entityId, lockType: lockType };
                Carousel.Dao.programToggleLock(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                });
            },
            modifyAdvert: function (entityId, advertEnable) {
//                var channel = Carousel.Dao.getChannel();
//                if (channel.alternatePlayCollection == null || channel.alternatePlayCollection.length == 0) {
//                    SystemDialog.queryAlert("<span style='color: red'> 无法添加，请先为频道添加备播视频！</span><br>广告期间需要使用备播码流")
//                    return;
//                }
                Carousel.Dao.cfgName.ad_selected = entityId;
                $("#advert_dlg").dialog("open");
//                var durationData = Carousel.Dao.adDuration();
//                if(durationData != null){
//                    var referKey = 1;
//                    $.each( durationData.data , function (i,element){
//                        if(element.val == advertDuration){
//                            referKey = element.key;
//                            return true;
//                        }
//                    })
//                }
                $("input[name=advertEnable][value='" + advertEnable + "']").prop("checked", true)
            },
            moveAdvert: function (entityId, moveType) {

            },
            recordDuration: function (dataOriginl) {
                Carousel.Config.durationMap = [];
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
                $.each(dataOriginl, function (i, element) {
                    var makeUpData = {};
                    makeUpData.id = element.id
                    makeUpData.referQipuId = element.carouselEpisode;
                    makeUpData.isLive = element.live;
                    makeUpData.startPlayTime = new Date(element.startPlayTime.replace(/-/g, "/")).getTime()
                    makeUpData.endPlayTime = new Date(element.endPlayTime.replace(/-/g, "/")).getTime();
                    makeUpData.pname = element.pname;
                    if (makeUpData.isLive == 2) {
                        makeUpData.duration = makeUpData.endPlayTime - makeUpData.startPlayTime;
                    } else {
                        makeUpData.duration = element.duration == null ? 0 : element.duration * 1000;
                    }
                    Carousel.Config.durationMap.push(makeUpData);
                })
            },
            addBreakHint: function (dataOriginl, tableName) {
                if (tableName == null) {
                    tableName = "#list"
                }
                var aimGrid = $(tableName);
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
                $.each(Carousel.Config.durationMap, function (i, element) {
                    if (element.duration > element.endPlayTime - element.startPlayTime) {
                        aimGrid.setCell(element.id, "endPlayTime", '', {backgroundColor: "#FFFF00"});
                    }
                });
            },
            showNoResult: function (dataLength, tableName) {
                if (tableName == null) {
                    tableName = "#list"
                }
                var jqGridTarget = $(tableName);
                var parentElement = jqGridTarget.parent();
                if (parentElement.find(".norecords").html() == null) {
                    parentElement.append('<div class="norecords">没有符合数据</div>');
                    parentElement.find(".norecords").hide();
                }
                if (dataLength == 0) {
                    parentElement.find(".norecords").show();
                } else {
                    parentElement.find(".norecords").hide();
                }
            },
            fillLineNo: function (tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                var params = _jqGrid.jqGrid("getGridParam");
                var index = (params.page - 1 ) * params.rowNum;
                var dataOriginal = _jqGrid.jqGrid("getDataIDs");
                $.each(dataOriginal, function (i, element) {
                    index++;
                    _jqGrid.setRowData(element, {"index": index });
                })
                console.log("更新行号");
            },
            toggleTwColumns: function (tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                var channel = Carousel.Dao.getChannel();
                if (channel['type'] == 11) {
                    _jqGrid.hideCol(["programName", "albumName", "channelName"]).trigger("reloadGrid");
                }else{
                    _jqGrid.hideCol(["twProgramName", "twAlbumName", "twChannelName"]).trigger("reloadGrid");
                }

            },
            notifyChangeBtnStatus: function (tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                var dataOriginal = _jqGrid.jqGrid("getDataIDs");
                $("button[name=btn_rule_start]").prop("disabled", "disabled");
                $("button[name=btn_rule_stop]").prop("disabled", "disabled");
                $("button[name=btn_rule_start]").hide();
                $("button[name=btn_rule_stop]").hide();
                if (dataOriginal == null) {
                    $("button[name=btn_rule_start]").show();
                    return;
                }
                if (dataOriginal.length == 0) {
                    $("button[name=btn_rule_start]").removeAttr("disabled");
                    $("button[name=btn_rule_start]").show();
                } else {
                    var checkData = _jqGrid.getRowData(dataOriginal[0]);
                    if (JSON.parse(checkData.hiddenData).status == 1) {
                        $("button[name=btn_rule_stop]").removeAttr("disabled");
                        $("button[name=btn_rule_stop]").show();
                    } else {
                        $("button[name=btn_rule_start]").removeAttr("disabled");
                        $("button[name=btn_rule_start]").show();
                    }
                }
            },


            checkSelectAble: function (dataOriginl, tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
//                var target = $("#cb_list");
//                target.unbind();
//                target.bind("click", this.mySelectedHandler);
                var currentDay = new Date();
                currentDay.setTime(currentDay.getTime() + 30 * 60 * 1000)
                var checkTime = Carousel.Util.formatDateTimeFormat(currentDay)
                $.each(dataOriginl, function (i, element) {
                    if (element.startPlayTime < checkTime) {
                        _jqGrid.find("input[type=checkbox][name=jqg_list_" + element.id + "]").prop("disabled", "disabled");
                        // $("#"+element.id).prop("disabled", "disabled");
                        //   _jqGrid.find("input[type=checkbox][name=jqg_list_"+element.id+"]").parent().find("td[aria-describedby=list_index]").unbind();
                    }

                });
            },
//            mySelectedHandler: function (event) {
//                var checkedFlag1 = $(event.currentTarget).prop("checked") == true;
//                var _jqGrid = $("#list");
//                var dataOriginl = Carousel.Dao.getFromCache("originalArr");
//                if (dataOriginl == null || dataOriginl.length == 0) {
//                    return;
//                }
//                var checkBoxArr = _jqGrid.find("input[type=checkbox][name^=jqg_list_]");
//                $.each(checkBoxArr, function (i, element) {
//                    if ($(element).prop("disabled") != true && $(element).prop("checked") != checkedFlag1) {
//                        _jqGrid.setSelection(dataOriginl[i].id, checkedFlag1);
//                    }
//                });
//                $(event.currentTarget).prop("checked", checkedFlag1)
//            },
            getAdvertStart: function (element) {

            },
            setColorTime: function (dataOriginl, tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
                var checkLength = dataOriginl.length - 1;
                var check2 = null;
                var makeStartColor = [];
                var makeEndColor = [];
                var makeMockColor = [];
                $.each(dataOriginl, function (i, element) {
                    if (element.qipuId == 0 && element.live == 1 && element.pname.indexOf("delete") == -1) {
                        makeMockColor.push(element.id);
                    }
                    if (i == checkLength) {
                        if (element.endPlayTime.length != 19 || "23:59:59" != element.endPlayTime.slice(-8)) {
                            if (element.endPlayTime.substr(0, 10) == element.startPlayTime.substr(0, 10)) {
                                makeEndColor.push(element.id);
                            }
                        }
                        return true;
                    }
                    check2 = dataOriginl[i + 1];
                    var checkDate1 = new Date(check2.startPlayTime).getTime() - check2.advertDuration * 1000;
                    var checkDate2 = new Date(element.endPlayTime).getTime();
                    var checkDate3 = Carousel.Util.formatDateTimeFormat(new Date(new Date(element.startPlayTime).getTime() - element.advertDuration * 1000));
                    if (checkDate2 > checkDate1) {
                        makeEndColor.push(element.id);
                        makeStartColor.push(check2.id);
                    } else if (checkDate1 > checkDate2) {
                        makeStartColor.push(check2.id);
                    }
                    if (Carousel.Dao.cfgName.yesterdayEndTime > element.endPlayTime) {
                        makeEndColor.push(element.id);
                        makeStartColor.push(element.id);
                    } else if (Carousel.Dao.cfgName.yesterdayEndTime > checkDate3) {
                        makeStartColor.push(element.id);
                    }
                });
                if (makeMockColor.length > 0) {
                    var dealArr = [];
                    $.each(makeMockColor, function (i, elementId) {
                        _jqGrid.setCell(elementId, "startPlayTime", '', {color: "#00cccc"});
                        _jqGrid.setCell(elementId, "endPlayTime", '', {color: "#00cccc"})
                    })
                }

                if (makeStartColor.length > 0) {
                    $.each(makeStartColor, function (i, elementId) {
                        _jqGrid.setCell(elementId, "startPlayTime", '', {color: "#ff0000"});
                    })
                }
                if (makeEndColor.length > 0) {
                    $.each(makeEndColor, function (i, elementId) {
                        _jqGrid.setCell(elementId, "endPlayTime", '', {color: "#ff0000"});
                    })
                }
            },

            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },

            getSearchParamsBySettings: function () {
                var response = Carousel.Dao.getPlatSettings();
                if (response == null) {
                    console.log("setting error");
                    return {};
                }
                var entity = response.data;
                var params = {};
                if (entity.checkPublishType == 1) {
                    params["filter_EQI_pagePublishStatus"] = 1;
                }
                if (entity.checkCopyRightType == 1) {
                    params["filter_GTI_copyrightOwnerId"] = 0;
                }
                if (entity.checkBossType == 0) {
                    params["filter_INI_isPurchase"] = "0,-100";
                } else if (entity.checkBossType == 1) {
                    params["filter_INI_isPurchase"] = "1,2";
                }
                var platformTypeResponse = Carousel.Dao.getPlatformType();
                $.each(platformTypeResponse.data, function (i, element) {
                    //   params["region_" + element.val] = 0;
                    if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                        params["region_" + element.val] = 1;
                    }
                });
                var platformReferResponse = Carousel.Dao.getPlatformRefer();
                $.each(platformReferResponse.data, function (i, element) {
                    //   params["filter_EQI_" + element.val] = 0;
                    if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                        params["filter_EQI_" + element.val] = 1;
                    }

                });
                console.log(" params:" + JSON.stringify(params))
                return params;
            },
            checkMultiCallBack: function (data, bindModel) {
                Carousel.Config.BIND_BATCH_ADD_MODEL = bindModel;
                console.log("checkMultiCallBack wait to do" + JSON.stringify(data));
                var result = data.result;
                var multiArr = [];
                var hasUsedArr = [];
                $.each(result, function (i, element) {
                    if (element.carouselEpisode > 0) {
                        hasUsedArr.push(element.carouselEpisode);
                    }
                });
                $.each(Carousel.Config.saveIds, function (i, element) {
                    if (hasUsedArr.indexOf(element) != -1) {
                        multiArr.push(element);
                    }
                });

                var hintMsg = [];
                if (Carousel.Config.invalidArr != null && Carousel.Config.invalidArr.length > 0) {
                    $.each(Carousel.Config.invalidArr, function (i, element) {
                        var idIndex = Carousel.Config.saveIds.indexOf(element);
                        if (idIndex != -1) {
                            Carousel.Config.saveIds.splice(idIndex, 1);
                        }
                        hintMsg.push(+"节目奇谱ID:<span style='color: red'>" + element + "</span>没有奇谱数据！");
                    })
                }
                if (multiArr != null && multiArr.length > 0) {
                    $.each(multiArr, function (i, element) {
                        hintMsg.push("节目奇谱ID:<span style='color: red'>" + element + "</span>,重复！");
                    })
                }
                // var dataArr = $("#listAdd1").jqGrid('getData');
                var responseData = Carousel.Dao.getFromCache("gridData1");
                var dataArr = responseData != null ? responseData.rows : [];
                var missPPSClientArr = [];
                var missPPSRegionArr = [];
                var missQIYIClientArr = [];
                var missQIYIRegionArr = [];
                $.each(dataArr, function (i, element) {
                    if (Carousel.Config.saveIds.indexOf(element.qipuId) != -1) {
                        if (element.hintMsgObj.missPPSClient === true) {
                            missPPSClientArr.push(element.qipuId);
                        }
                        if (element.hintMsgObj.missPPSRegion === true) {
                            missPPSRegionArr.push(element.qipuId);
                        }
                        if (element.hintMsgObj.missQIYIClient === true) {
                            missQIYIClientArr.push(element.qipuId);
                        }
                        if (element.hintMsgObj.missQIYIRegion === true) {
                            missQIYIRegionArr.push(element.qipuId);
                        }
                    }
                })
                var remindLength = 0;
                var checkMsgArr = [ missPPSClientArr, missPPSRegionArr, missQIYIClientArr , missQIYIRegionArr ];
                var platformCheck = [Carousel.Config.Hint.PPS_CLIENT_HINT , Carousel.Config.Hint.PPS_REGION_HINT, Carousel.Config.Hint.QIYI_CLIENT_HINT, Carousel.Config.Hint.QIYI_REGION_HINT];
                var platformMsg = [];
                $.each(checkMsgArr, function (i, checkArr) {
                    if (checkArr.length > 0) {
                        remindLength = checkArr.length;
                        if (remindLength > 3) {
                            checkArr.length = 3;
                            platformMsg.push("节目奇谱ID " + checkArr.join(",") + "等" + remindLength + "个节目" + platformCheck[i]);
                        } else {
                            platformMsg.push("节目奇谱ID " + checkArr.join(",") + platformCheck[i]);
                        }
                    }
                })
                if (platformMsg.length > 0) {
                    platformMsg.push(Carousel.Config.Hint.QUERY_ADD);
                }
                hintMsg = hintMsg.concat(platformMsg);
                if (hintMsg.length > 0) {
                    $("#batchResponseDiv").find("div[sign=detail]").html(hintMsg.join("<br>"));
                    $("#batchResponseDiv").dialog("open");
                } else {
                    this.batchAddByBindModel()
                }
            },
            removeDisAble: function () {
                $("button[name=btn_addType1]").removeAttr("disabled");
                $("button[name=btn_addType2]").removeAttr("disabled");
                $("button[name=btn_addType3]").removeAttr("disabled");
            },
            addDisAble: function () {
                $("button[name=btn_addType1]").attr("disabled", "disabled");
                $("button[name=btn_addType2]").attr("disabled", "disabled");
                $("button[name=btn_addType3]").attr("disabled", "disabled");
            },
            addLibraryDisAble: function () {
                $("button[name=btn_rule_start]").attr("disabled", "disabled");
                $("button[name=btn_rule_stop]").attr("disabled", "disabled");
            },
            removeLibraryDisAble: function () {
                $("button[name=btn_rule_start]").removeAttr("disabled");
                $("button[name=btn_rule_stop]").removeAttr("disabled");
            },

            batchAdd: function () {
                if (Carousel.Config.saveIds == null) {
                    console.log("saveIds is empty");
                    return;
                }
                Carousel.Util.addDisAble();
                console.log("sendId" + JSON.stringify(Carousel.Config.saveIds));
                Carousel.Dao.batchAdd({data: JSON.stringify(Carousel.Config.saveIds), beginTime: Carousel.Config.dateTime, fatherId: Carousel.Dao.channelId }, function (data) {
                    Carousel.Util.removeDisAble();
                    if (data != null) {
                        if (data.code == "A00000") {
                            EpgWeb.Plugin.showTips({content: data.msg});

                            $("#cb_listAdd1").click();
                            if ($("#cb_listAdd1").prop("checked") == true) {
                                $("#cb_listAdd1").click()
                            }
                        } else {
                            SystemDialog.queryAlert(data.msg);
                        }
                    } else {
                        console.log("data" + JSON.stringify(data));
                    }
                });
            },
            episodeBatchAdd: function () {
                if (Carousel.Config.saveIds == null) {
                    console.log("saveIds is empty");
                    return;
                }
                Carousel.Util.addDisAble();
                console.log("sendId" + JSON.stringify(Carousel.Config.saveIds));
                Carousel.Dao.episodeBatchAdd({data: JSON.stringify(Carousel.Config.saveIds), fatherId: Carousel.Dao.channelId }, function (data) {
                    Carousel.Util.removeDisAble();
                    if (data != null) {
                        if (data.code == "A00000") {
                            $("#cb_listAdd1").click();
                            if ($("#cb_listAdd1").prop("checked") == true) {
                                $("#cb_listAdd1").click()
                            }
                            $("#queryMessage").dialog("open");
                        } else {
                            var msg = data.msg == null ? "添加出现异常" : JSON.parse(data.msg).ret_msg;
                            EpgWeb.Plugin.showTips({content: msg, type: "error" });
                        }
                    } else {
                        console.log("data" + JSON.stringify(data));
                    }
                });
            },
            episodeIndexMove: function (entityId, targetId) {
                var sendData = {id: entityId, aimIdx: targetId, channelId: Carousel.Dao.channelId};
                Carousel.Dao.episodeIndexMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                })
            },
            notifyRuleChangeStatus: function (execStatus, callback) {
                var data = { channelId: Carousel.Dao.channelId, execStatus: execStatus};
                Carousel.Dao.notifyRuleChangeStatus(data, function (data) {
                    if (data == null || data.code != "A00000") {
                        if (data.msg != null) {
                            SystemDialog.queryAlert(data.msg)
                        }
                    }

                    Carousel.Util.queryVirtualRule({ channelId: Carousel.Dao.channelId}, function (flag) {
                        console.log("notifyRuleChangeStatus callback wait to do ");
                        $("#list").trigger("reloadGrid")
                    });
                })

            },
            checkQipuPlatformControl: function (callback, ret) {
                var task = Carousel.Task.checkForQipuDataTask(Carousel.Util.multiCheckHandler);
                var dataArr = [];
                var requestData = null;
                var currentTime = Date.now();

                Carousel.Dao.putToCache("originalArr", ret.result);
                $.each(ret.result, function (i, element) {
                    requestData = {url: EpgWeb.urlConfig.getQiPuBaseUrl(element["qipuId"]), type: "get"};
                    dataArr.push({"request": JSON.stringify(requestData), timeSign: currentTime });
                });
                Carousel.Config.lockFlag = true;
                $("#loadLegoMessage").dialog("open");
                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                var timerId = setInterval(function () {
                    if (!Carousel.Config.lockFlag) {
                        clearInterval(timerId);
                        $("#loadLegoMessage").dialog("close");
                        callback(ret);
                    }
                }, 160)
                EpgWeb.ajaxQueue.startLoad();
            },
            multiCheckHandler: function (options) {
                console.log(options.acceptArr);
                var playControlArr = null;
                var checkPlatforms = Carousel.Dao.getPlatformType().data;
                var originalArr = Carousel.Dao.getFromCache("originalArr");
                $.each(options.acceptArr, function (i, element) {
                    var original = originalArr[element.nodeIndex ];
                    if (element.responseData == null) {
                        original.illegal = true;
                        return true;
                    }
                    playControlArr = element.responseData["access_play_control"];
                    if (null == playControlArr && ( null == element.responseData["available_status"] || "OFFLINE_COPYRIGHT" === element.responseData["available_status"])) {
                        original.illegal = true;
                        return true;
                    }
                    if ($.isArray(playControlArr)) {
                        var temp = {};
                        $.each(playControlArr, function (index, elementChild) {
                            var platformObject = Carousel.Util.decodePlayPlatform(elementChild);
                            if (platformObject.platName != null) {
                                temp[platformObject.platName] = platformObject;
                            }
                        })

                        original.controlObj = temp
                        var qipuPlatformData = [];
                        var qipuRegionData = [];
                        var hintMsgObj = {
                            missQIYIClient: false,
                            missPPSClient: false,
                            missQIYIRegion: false,
                            missPPSRegion: false
                        };
                        $.each(checkPlatforms, function (index, element) {
                            var ppsFlag = element.val.indexOf("PPS") !== -1;
                            if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                                qipuPlatformData.push(element.val)
                                if (ppsFlag) {
                                    hintMsgObj.missPPSClient = true;
                                } else {
                                    hintMsgObj.missQIYIClient = true;
                                }
                            }
                            if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                                qipuRegionData.push(element.val);
                                if (ppsFlag) {
                                    hintMsgObj.missPPSRegion = true;
                                } else {
                                    hintMsgObj.missQIYIRegion = true;
                                }
                            }
                        });
                        original["qipuPlatformData"] = qipuPlatformData;
                        original["qipuRegionData"] = qipuRegionData;
                        original["hintMsgObj"] = hintMsgObj;

                        console.log(element.responseData["id"] + "| qipuPlatformData : " + JSON.stringify(original["qipuPlatformData"]));
                        console.log(element.responseData["id"] + "| qipuRegionData: " + JSON.stringify(original["qipuRegionData"]));
                        console.log(element.responseData["id"] + "| hintMsgObj: " + JSON.stringify(original["hintMsgObj"]));
                    }

                    // TW
                    channelbase = Carousel.Dao.getChannel();
                    if(channelbase != null && channelbase['type'] == 11) {
                        localbaseArr = element.responseData['local_base'];
                        if(localbaseArr != null) {
                            $.each(localbaseArr, function(index, local) {
                                if(local['language'] == 'zh_TW' && local['display_name'] != null) {
                                    original['displayName'] = local['display_name'];
                                }
                            })
                        }
                    }

                });
                Carousel.Config.lockFlag = false;
            },

            isCarouselCheck: function (channelData) {
                if (channelData.liveType != 3) {
                    EpgWeb.Plugin.showTips({content: Carousel.Config.Hint.NOT_CAROUSEL, type: "error"});
                    setTimeout(function () {
                        window.location.href = "/epg/program_list.html?fatherId=" + channelData.id;
                    }, 2000)
                    return false;
                }
                return true;
            },

            //
            queryTotalNum: function (entityId, handler) {
                var params = Carousel.Util.getSearchParamsBySettings();
                params["filter_EQL_albumId"] = entityId;
                params["filter_GTL_qipuId"] = 0;
                params["filter_GEL_duration"] = 60000;
                params["filter_EQI_contentType"] = 1;
                params["t"] = 0;
                params["page.order"] = "asc,asc";
                params["page.orderBy"] = "videoOrder,createTime";
                params["page.pageSize"] = 50;
                params["page.pageNo"] = 1;

                var QueryComponent = {
                    referElement: Carousel.Config.ruleSelectElement,
                    totalCount: 0,
                    params: params,
                    query: function (entityId) {
                        var self = this;
                        var requestData = {url: Carousel.Constant.thirdUrl_apis_search_area_url, type: "get",
                            params: self.params,
                            needCookie: true};
                        var options = {
                            url: Carousel.urlConfig.redirect,
                            type: "post",
                            dataType: "json",
                            data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        }

                        $.ajax({
                            type: options.type,
                            url: options.url,
                            dataType: options.dataType,
                            beforeSend: function (request) {
                                request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                            },
                            data: options.data,
                            success: function (data) {
                                self.totalCount += data.data.result.length;
                                if (true === data.data.hasNext) {
                                    self.params["page.pageNo"] = data.data.nextPage;
                                    self.query(entityId);
                                } else {
                                    $("input[name=actualNum]").val(self.totalCount);
                                    if (handler != null) {
                                        handler();
                                    }
                                }
                            },
                            error: function (data) {
                                EpgWeb.Plugin.showTips({
                                    content: "请求失败",
                                    type: "error"
                                })
                                $("input[name=actualNum]").val(0);
                            }});
                    }
                };
                QueryComponent.query(entityId);
            },
            transToCheckKey: function (sendData) {
                var dataArr = [];
                dataArr.push(sendData.qipuId);
                dataArr.push(sendData.startNum);
                dataArr.push(sendData.repeatedStatus);
                dataArr.push(sendData.followedStatus);
                dataArr.push(sendData.followNum);
                dataArr.push(sendData.startTime);
                return dataArr.join("|")
            },
            queryVirtualRule: function (data, callback) {
                Carousel.Util.addLibraryDisAble();
                Carousel.Dao.automationList(data, function (data) {
                    if (data != null && data.code == "A00000") {
                        Carousel.Config.IS_RULE_RUNNING = data.data.result.length > 0 && data.data.result[0].status == 1;
                        Carousel.Util.updateRuleStatusBtn(Carousel.Config.IS_RULE_RUNNING);
                        callback(true);
                    } else {
                        var msg = data != null ? data.msg : "";
                        EpgWeb.Plugin.showTips("初始化异常!" + msg);
                        callback(false);
                    }
                    Carousel.Util.removeLibraryDisAble();
                })
            },
            updateRuleStatusBtn: function (isRunning) {
                if (isRunning) {
                    $("button[name=btn_rule_start]").hide();
                    $("button[name=btn_rule_stop]").show();
                } else {
                    $("button[name=btn_rule_start]").show();
                    $("button[name=btn_rule_stop]").hide();
                }
            },
            openHistory: function (entityId) {
                Carousel.Dao.doAuthData({
                    url: '/epg/channel_log.html',
                    doSuccess: function () {
                        Carousel.Config.AUTH_LOG_DETAIL = true;
                    },
                    doFinal: function () {
                        var tableConfig = $.extend(true, {}, Carousel.Config.TABLE_LOG);
                        tableConfig.width = Carousel.Config.AUTH_LOG_DETAIL ? 875 : 425
                        var colModel = tableConfig.colModel;
                        var newColModel = [];
                        var colModelConfig = Carousel.Config.TABLE_COLMODEL_CONFIG;

                        $.each(colModel, function (i, model) {
                            newColModel.push(colModelConfig[model]);
                        });
                        tableConfig.colModel = newColModel;
                        tableConfig.colModel[4].hidden = !Carousel.Config.AUTH_LOG_DETAIL;
                        $('#logList').jqGrid(tableConfig);
                        $("#programLogDiv").dialog({
                            title: "历史记录",
                            autoOpen: false,
                            width: Carousel.Config.AUTH_LOG_DETAIL ? 900 : 450,
                            height: 600,
                            modal: true,
                            dialogClass: 'alert',
                            open: function () {
                                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                            }
                        });
                        $("#programLogDiv").dialog("open");
                        $('#logList').jqGrid('setGridParam', {
                            page: 1,
                            datatype: "json",
                            postData: {id: entityId}
                        }).trigger('reloadGrid');
                    }
                })
            },
            batchAddByBindModel: function () {
                if (Carousel.Config.BIND_BATCH_ADD_MODEL != null) {
                    console.log("BIND_BATCH_ADD_MODEL:" + Carousel.Config.BIND_BATCH_ADD_MODEL);
                    this[Carousel.Config.BIND_BATCH_ADD_MODEL]();
                }
            },
            // automation rule start
            delAutomationRule: function (entityId, fatherId) {
                Carousel.Dao.delAutomationRule({ids: entityId, fatherId: fatherId}, function (data) {
                    if (data != null && data.msg != null) {
                        SystemDialog.queryAlert(data.msg);
                    } else {
                        console.log("callbackHandler no return data");
                    }
                    $("#ruleList").trigger("reloadGrid")
                });
            },
            batchDelAutomationRule:function(entityArr){
                if (entityArr.length == 0) {
                    return
                }
                this.delAutomationRule( entityArr.join(","),Carousel.Dao.getChannel().id);
            },
            checkMultiAutomationRule: function (sendData, tableName) {
                var dataArr = $(tableName).getRowData();
                //.jqGrid('getData');
                var uniqueKey = "" + sendData.qipuId;
                var findSamekey = false;
                $.each(dataArr, function (i, element) {
                    if (JSON.parse(element.hiddenData).qipuId == uniqueKey) {
                        findSamekey = true;
                        return false;
                    }
                });
                return findSamekey;
            },
            prepareAutomationRuleData: function (element) {
                var sendObject = {};
                sendObject.fatherId = Carousel.Dao.getChannel().id;
                sendObject.showName = element.value;
                sendObject.channelTag = element.channelName;
                sendObject.qipuId = element.id;

                sendObject.copyrightEndTime = "";

                var queryMsg = "";
                if (element.copyrightEndTime == -100) {
                    sendObject.copyrightEndTime = "-100";
                } else if (element.copyrightEndTime != null && element.copyrightEndTime != "" && element.copyrightEndTime > 0) {
                    sendObject.copyrightEndTime = Carousel.Util.formatter.copyrightEndTime(element.copyrightEndTime);
                }
                //epg 收费状态(1：免费 2：收费)
                sendObject.bossStatus = 1;
                if (element.isPurchase !== "") {
                    sendObject.bossStatus = element.isPurchase === 1 ? 2 : 1
                }
                //epg 发布状态(1：未发布 2：已发布)
                sendObject.publishStatus = 2
                sendObject.totalNum = element.totalNum;
                sendObject.pageUrl = element.pageUrl;
                if (sendObject.pageUrl == null) {
                    sendObject.pageUrl = "";
                }
                sendObject.actualNum = parseInt($("input[name=actualNum]").val());
                return sendObject;
            },
            addAutomationRule: function (allowMulti) {
                var parent = $("#carouselAutoRuleView");
                var element = Carousel.Config.ruleSelectElement
                if (element == null) {
                    console.log("no element selected")
                    return;
                }
                var checkArr = [];
                checkArr.push({value: element.id + "", error: "不允许手动修改对象奇谱Id", type: "eq", other: parent.find("input[name=_" + parent.find("select[name=frontSuggestType]").val() + "]").attr("data-id") })
                if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt case check Fail")
                    return;
                }
                var sendObject = Carousel.Util.prepareAutomationRuleData(element);
                //开始
                var hasSame = Carousel.Util.checkMultiAutomationRule(sendObject)
                console.log("hasSame:" + hasSame);
                if (!allowMulti && hasSame) {
                    SystemDialog.queryConfirm("专辑《" + sendObject.showName + "》已存在，是否确认再次添加", function (flag) {
                        if (flag == true) {
                            Carousel.Util.addAutomationRule(true);
                        }
                    })
                    return;
                }

                var msg = [];
                if (element.hintMsgObj.missPPSClient) {
                    msg.push(Carousel.Config.ErrorMsg.PPS_CLIENT_MSG)
                }
                if (element.hintMsgObj.missQIYIClient) {
                    msg.push(Carousel.Config.ErrorMsg.QIYI_CLIENT_MSG);
                }
                if (element.hintMsgObj.missPPSRegion) {
                    msg.push(Carousel.Config.ErrorMsg.PPS_REGION_MSG);
                }
                if (element.hintMsgObj.missQIYIRegion) {
                    msg.push(Carousel.Config.ErrorMsg.QIYI_REGION_MSG);
                }
                if (msg.length > 0) {
                    SystemDialog.queryConfirm(msg.join("<br>"), function (flag) {
                        if (flag === true) {
                            $("#carouselAutoRuleView").find("button[name=addRule]").prop("disabled", "disabled");
                            var task = Carousel.Task.sendAddRuleTask(sendObject)
                            Carousel.ajaxManager.push(task.regName, task.options, null, true);
                            Carousel.ajaxManager.startLoad();
                        }
                    })
                } else {
                    $("#carouselAutoRuleView").find("button[name=addRule]").prop("disabled", "disabled");
                    var task = Carousel.Task.sendAddRuleTask(sendObject)
                    Carousel.ajaxManager.push(task.regName, task.options, null, true);
                    Carousel.ajaxManager.startLoad();
                }
            },
            changeStatusAutomationRule:function(execStatus){
                var sendData = { channelId: Carousel.Dao.getChannel().id  , execStatus: execStatus}
                Carousel.Dao.changeStatusAutomationRule( sendData,function(data){
                        if(data == null){
                            SystemDialog.queryAlert(data.msg);
                        }else if(data.code == "A00000"){
                        }else if( data.msg != null ){
                            SystemDialog.queryAlert(data.msg)
                        }
                    $("#ruleList").trigger("reloadGrid")
                } )
            }
            // automation rule end
        })


    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.Task.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel.Task',['require','exports','module'],function (require, exports, module) {
        Carousel.Task = $.extend({}, EpgWeb.Task, {
            getLiveProgramTypeTask: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            },
            getContentTypeTask: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            },
            platformsTask: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            },
            getLogType:function(taskName){
                var self = this;
                return self.getConfigType(taskName)
            },
            getAdDuration:function(taskName){
                var self = this;
                return self.getConfigType(taskName ,function (data) {
                    var selectJDom = $("select[name=advert_select]");
                    $.each(data.data, function (index, obj) {
                        $("<option>", {
                            value:obj.key,
                            html: obj.descr
                        }).appendTo(selectJDom);
                    });
                })
            },
            getPlatformReferTask: function (taskName) {
                var self = this;
                return self.getConfigType(taskName)
            },
            platSettingsTask:function( regName,data){
                return {
                    regName: regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.platSettingsGetUrl,
                        dataType: "json",
                        data: data
                    }
                }
            },
            checkForQipuDataTask:function ( callbackHandler ) {
            return {
                regName: "checkForQipu",
                options: {
                    url: EpgWeb.urlConfig.redirect,
                    dataType: "json",
                    type: "post"
                },
                handler: function (options) {
                    callbackHandler( options );
                }
            }
        }
        });
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.Grid.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel.AutomationRuleGrid',['require','exports','module'],function (require, exports, module) {
        Carousel.AutomationRuleGrid = function (options) {
            this.dao = Carousel.Dao;
            this.config = Carousel.Config;
            this.task = Carousel.Task;
            this.options = options || {};
        };
        Com.inherits(Carousel.AutomationRuleGrid, Ancestor.Grid).extend({
            runAutomationRule: function () {
                var self = this;
                self.$grid = self.options.$grid;
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramTypeTask(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.platformsTask(self.dao.cfgName.PlayPlatform))
                taskArr.push(self.task.getPlatformReferTask(self.dao.cfgName.PlatformRefer));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: self.dao.channelId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function(){
                    self.startAutomationRule();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            initSuggest: function () {
            },
            initDialogs: function () {
            },
            bindEvent: function () {
                $("button[name=btn_rule_start]").bind("click", function (event) {
                    Carousel.Util.changeStatusAutomationRule(1)
                })
                $("button[name=btn_rule_stop]").bind("click", function (event) {
                    SystemDialog.queryConfirm(Carousel.Config.Hint.STOP_RULE_HINT, function (flag) {
                        if (flag === true) {
                              Carousel.Util.changeStatusAutomationRule(0)
                        }
                    })
                })
                $("#carouselAutoRuleView").find("button[name=addRule]").bind("click", function (event) {
                      Carousel.Util.addAutomationRule();
                })
            },
            startAutomationRule: function () {
                var self = this;
                var channelData = self.dao.getChannel();
                if (!Carousel.Util.isCarouselCheck(channelData)) {
                    return;
                }
                self.bindEvent();
                self.initSuggest();
                self.initDialogs();
                self.initRuleList();
                self.fillRuleListGrid();
            },
            initRuleList: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_AUTOMATION_RULE);
                self.$grid.jqGrid(gridConfig);

                self.$grid.jqGrid('navGrid', "#pagerAutoRule", {
                    edit: false,
                    add: false,
                    del: false,
                    search: false,
                    refresh: false
                });
                self.$grid.jqGrid('navButtonAdd', "#pagerAutoRule", {
                    caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                    onClickButton: function () {
                        var gridElement = $("#ruleList");
                        var dataOriginl = gridElement.jqGrid("getRowData");
                        var interruptFlag = false;
                        $.each(dataOriginl, function (i, rowData) {
                            if (JSON.parse(rowData.hiddenData).status == 1) {
                                interruptFlag = true;
                                return false;
                            }
                        })
                        if (interruptFlag) {
                            SystemDialog.queryAlert("规则执行中不能删除");
                            return;
                        }

                        var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                        var ids = [];
                        $.each(selectedtrArr, function (i, element) {
                            ids.push(parseInt($(element).attr("id")));
                        });

                        if (ids.length == 0) {
                            return;
                        }
                        Carousel.Util.batchDelAutomationRule(ids);
                    }, position: "last", title: "批量删除", cursor: "pointer"
                });
            },
            fillRuleListGrid:function(){
                var self = this;
                var channelData = self.dao.getChannel();
                self.$grid.clearGridData();
                self.$grid.setGridParam({page: 1, url: EpgWeb.urlConfig.automationListUrl, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: {channelId: channelData.id}}).trigger("reloadGrid");
            }
        })
    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.Grid.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
define(
    '../carousel/Carousel.Grid',['require','exports','module'],function (require, exports, module) {
        Carousel.Grid = function (options) {
            this.dao = Carousel.Dao;
            this.config = Carousel.Config;
            this.task = Carousel.Task;
            this.options = options || {};
        };
        Com.inherits(Carousel.Grid, Ancestor.Grid).extend({
            //--------CarouselEdit start==========/
            runDayList: function () {
                var self = this;
                self.dayListUseDlg();
                $("button[name=btn_automation_rule]").hide();
                $("button[name=btn_auto_rule]").hide();
                $("button[name=btn_automation_library]").hide();

                self.$grid = self.options.$grid
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramTypeTask(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getContentTypeTask(self.dao.cfgName.ContentType));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
          //      taskArr.push(self.task.getAdDuration(self.dao.cfgName.Ad_duration));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: self.dao.channelId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startDayList();
                    self.initAdvertDialog();
                });
                EpgWeb.ajaxQueue.startLoad();
            },

            startDayList: function (options, callback) {
                var self = this;
                var channelData = self.dao.getChannel();
                if (!Carousel.Util.isCarouselCheck(channelData)) {
                    return;
                }
                switch (channelData.automation) {
                    case 1:
                        $("button[name=btn_automation_rule]").show();
                        break;
                    case 0:
                        $("button[name=btn_auto_rule]").show();
                        break;
                    case 2:
                        $("button[name=btn_automation_library]").show();
                        break;
                }
                self.initDayList();
                self.bindListBasicEvent()
                self.initWeekToolBar();
                self.initAdvertDialog();
            },
            initDayList: function (options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                self.$grid.jqGrid(gridConfig);
                self.bindDayTListEvent();
            },
            bindDayTListEvent: function () {
                var self = this;
                $("<span style='color:#187ddb'>直播视频只能回看二天！</span>").appendTo($("#t_list"));
                var bdiv = $(".ui-jqgrid-bdiv");

                $("<label style='width: 40px;float:right;'>PM</label>").bind("click", function () {
                    if (bdiv[0].scrollHeight <= bdiv[0].clientHeight) {
                        return;
                    }
                    var allDate = self.$grid.jqGrid("getRowData");
                    var checkPM = "";
                    var interrupt = 0;
                    for (var i = 0; i < allDate.length; i++) {
                        checkPM = allDate[i].startPlayTime.substr(11);
                        if (checkPM >= "12:00:00") {
                            interrupt = i;
                            break;
                        }
                    }
                    bdiv.scrollTop(interrupt / allDate.length * bdiv[0].scrollHeight)
                }).appendTo($("#t_list"));
                $("<label style='width: 40px;float:right;'>AM</label>").bind("click", function () {
                    bdiv.scrollTop(0)
                }).appendTo($("#t_list"));
                self.$grid.jqGrid('navGrid', "#pager", { edit: false, add: false, del: false, search: false, refresh: false});
                self.$grid.jqGrid('navButtonAdd', "#pager", {caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                    onClickButton: function () {
                        console.log("self del");
                        var gridElement = self.$grid;
                        var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                        var ids = [];
                        $.each(selectedtrArr, function (i, element) {
                            ids.push(parseInt($(element).attr("id")));
                        })
                        if (ids.length == 0) {
                            return
                        }
                        self.dao.programBatchDel({ids: "[" + ids.join(",") + "]", dateTime: self.config.dateTime, channelId: self.dao.channelId}, function (data) {
                            Carousel.Util.reloadHandler(data);
                        });
                    }, position: "last", title: "批量删除", cursor: "pointer"});
            },


            bindListBasicEvent: function () {
                var self = this;
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                $("button[name=btn_auto_sort]").bind("click", function (event) {
                    console.log("wait to deal");
                    $("button[name=btn_auto_sort]").attr("disabled","disabled")
                    var selectedId = self.$grid.jqGrid("getGridParam", "selrow")
                    console.log(" selectedId " + selectedId);
                    var selectedData = self.$grid.jqGrid('getRowData', selectedId);
                    console.log("selectedData:" + JSON.stringify(selectedData));
                    self.dao.gridSort({fatherId: self.dao.channelId, sortDate: self.config.dateTime + " 00:00:00"}, function (data) {
                        $("button[name=btn_auto_sort]").removeAttr("disabled");
                        Carousel.Util.reloadHandler(data);
                    });
                })
                $("button[name=btn_insert]").bind("click", function (event) {
                    var selectedId = self.$grid.jqGrid("getGridParam", "selrow")
                    var toHref = "/epg/carousel_insert.html?fatherId=" + self.dao.channelId;
                    console.log(" selectedId " + selectedId);
                    var currentDay = EpgWeb.Util.formatDateTimeFormat(new Date())
                    var startTime = null;
                    if (selectedId != null) {
                        var selectedData = self.$grid.jqGrid('getRowData', selectedId);
                        startTime = selectedData.endPlayTime;
                        if (selectedData.endPlayTime.substr(0, 10) > selectedData.startPlayTime.substr(0, 10)) {
                            EpgWeb.Plugin.showTips({content: "不能选择跨天节目的结束时间!", type: "error"})
                            return
                        }
                    } else {
                        startTime = self.config.dateTime + " 00:00:00";
                    }
                    if (currentDay.substr(0, 10) > startTime.substr(0, 10)) {
                        EpgWeb.Plugin.showTips({content: "插入天数不能小于操作天数", type: "error"})
                        return;
                    }
                    toHref += "&startTime=" + startTime;
                    Carousel.Util.openNewHtml(toHref);
                })
                $("button[name=btn_auto_rule]").bind("click", function (event) {
                    Carousel.Util.openNewHtml("/epg/carousel_rule.html?fatherId=" + self.dao.channelId);
                })
                $("button[name=btn_automation_rule]").bind("click", function (event) {
                    Carousel.Util.openNewHtml("/epg/carousel_automation_rule.html?fatherId=" + self.dao.channelId);
                });
                $("button[name=btn_automation_library]").bind("click", function (event) {
                    Carousel.Util.openNewHtml("/epg/carousel_automation_library.html?fatherId=" + self.dao.channelId);
                });
                self.dao.doAuthData({
                    url: '/epg/config_manager.html',
                    doSuccess: function () {
                        $("button[name=btn_search_config]").show();
                        $("button[name=btn_search_config]").bind("click", function (event) {
                            Carousel.Util.openNewHtml("/epg/config_manager.html?id=" + self.dao.channelId);
                        });
                    }
                })
            },


            getListParam: function () {
                var self = this;
                return  {startDate: Carousel.Config.dateTime + " 00:00:00", endDate: Carousel.Config.dateTime + " 23:59:59", fatherId: self.dao.channelId, pageSize: 40}
            },

            //--------CarouselEdit End==========/
            //--------CarouselInsert  start==========/
            runInsertList: function () {
                var self = this;
                self.insertUseDlg();
                var startTime = Com.url.getParameter("startTime")
                if (startTime == null) {
                    EpgWeb.Plugin.showTips({content: "参数异常", type: "error"})
                    return;
                }
                self.$grid1 = self.options.$gridType1;
                self.$grid2 = self.options.$gridType2;
                var taskArr = [];
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: self.dao.channelId}));
                }
                taskArr.push(self.task.platSettingsTask(self.dao.cfgName.platSettings, {channelId: self.dao.channelId}));
                taskArr.push(self.task.getLiveProgramTypeTask(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.platformsTask(self.dao.cfgName.PlayPlatform))
                taskArr.push(self.task.getPlatformReferTask(self.dao.cfgName.PlatformRefer));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startInsertList();
                });
                Carousel.Config.dateTime = EpgWeb.Util.formatDateTimeFormat(new Date(startTime.replace(/-/g, "/")))
                EpgWeb.ajaxQueue.startLoad();
            },
            startInsertList: function () {
                var self = this;
                self.initListAddType1Grid();
                self.initListAddType2Grid();
                self.bindInsertEvent();
            },
            initListAddType1Grid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST_ADD_TYPE1);
                self.$grid1.jqGrid(gridConfig);
            },
            initListAddType2Grid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST_ADD_TYPE2);
                self.$grid2.jqGrid(gridConfig);
            },
            bindInsertEvent: function () {
                var self = this;
                var parent = $("#addProgramView");
                parent.find("button[name=queryProgram]").bind("click", function (event) {
                    self.queryProgram();
                });
                parent.find("button[name=btn_addType1]").bind("click", function (event) {
                    self.batchInsertLegoProgram("listAdd1");
                });
                parent.find("button[name=btn_addType2]").bind("click", function (event) {
                    self.batchInsertLiveProgram("listAdd2")
                });
                parent.find("button[name=btn_addType3]").bind("click", function (event) {
                    self.batchInsertCarouselLibrary("listAdd1");
                });


                Carousel.Util.bindDate("minDateTime", "maxDateTime");
                parent.find("button[name=btn_addType3]").hide();
                var channelData = self.dao.getChannel();
                if( 2 == channelData.automation  ){
                    parent.find("button[name=btn_addType3]").show();
                }

                var selectTarget = $("#addProgramView").find("select[name=insertType]");
                selectTarget.bind("change", function (event) {
                    var typeMode = selectTarget.val();
                    $("#addType1").hide();
                    $("#addType1").clearGridData();
                    $("#addType2").hide();
                    $("#addType2").clearGridData();
                    if (typeMode == "type1") {
                        $("#addType1").show();
                        $("#dateTimeDiv").hide();
                        $("#div_new_type1").show();
                        $("#videoOrderDiv").show();
                        $("#div_albumName_typ1").show();
                        $("#div_tags_typ1").show();
                        $("input[type=text]").val("");
                    } else {
                        $("#addType2").show();
                        $("#dateTimeDiv").show();
                        $("#div_new_type1").hide();
                        $("#videoOrderDiv").hide();
                        $("#div_albumName_typ1").hide();
                        $("#div_tags_typ1").hide();
                        $("input[type=text]").val("");
                    }
                    $("input[name=minTime]").val(60);
                })
                selectTarget.change();
            },

            batchInsertLegoProgram: function (tableId) {
                var self = this;
                var gridElement = $("#" + tableId);
                var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                var ids = [];
                $.each(selectedtrArr, function (i, element) {
                    ids.push(parseInt($(element).attr("id")));
                })
                if (ids.length == 0) {
                    return;
                }
                // doSort ;
                ids = self.doSort(ids);
                Carousel.Util.addDisAble();
                Carousel.Config.saveIds = ids;
                self.checkMulti();
                console.log("ids " + JSON.stringify(ids));
            },

            checkMulti: function () {
                var self = this;
                var lDateFormat = self.config.dateTime.substr(0, 10);
                var sendData = {startDate: lDateFormat + " 00:00:00", endDate: lDateFormat + " 23:59:59", fatherId: self.dao.channelId, pageSize: 2000}
                self.dao.getProgramList(sendData, function (rdata) {
                    if (rdata != null) {
                        Carousel.Util.checkMultiCallBack(rdata.data,"batchAdd");
                    } else {
                        console.log("getProgramListTask fail");
                    }
                })
            },
            checkLibraryMulti:function(){
                var self = this;
                var sendData = {channelId: self.dao.channelId, pageSize: 2000}
                self.dao.getCarouselEpisodeList (sendData, function (rdata) {
                    if (rdata != null) {
                        if( rdata.code != "A00000"){
                            SystemDialog.queryAlert(rdata.msg);
                            return ;
                        }
                        $.each(rdata.data.result,function(i,element){
                            element.carouselEpisode = element.qipuId;
                        })
                        Carousel.Util.checkMultiCallBack(rdata.data,"episodeBatchAdd");
                    } else {
                        console.log("checkLibraryMulti fail");
                    }
                })
            },

            doSort: function (ids) {
                var self = this;
                var responseData = self.dao.getFromCache("gridData1");
                var dataArr = responseData != null ? responseData.rows : [];
                var sortArr = [];
                $.each(dataArr, function (i, element) {
                    if (ids.indexOf(element.qipuId) != -1) {
                        sortArr.push(element);
                    }
                });
                sortArr.sort(function (a, b) {
                    if (a.videoOrder != b.videoOrder) {
                        return a.videoOrder > b.videoOrder;
                    }
                    return a.globalPublishDate > b.globalPublishDate;
                });
                var afterSort = [];
                $.each(sortArr, function (i, element) {
                    afterSort.push(element.qipuId);
                })
                console.log("ids " + JSON.stringify(ids) + " afterSort:" + JSON.stringify(afterSort));
                return afterSort;
            },


            queryProgram: function () {
                var self = this;
                var queryObject = {};
                var parent = $("#addProgramView");
                var isLiveType = parent.find("select[name=insertType]").val() == "type2";
                var queryName = jfUtil.simplized($.trim(parent.find("input[name=queryName]").val()));
                var queryQipuId = $.trim(parent.find("input[name=qipuId]").val());
                queryObject.queryName = queryName;
                queryObject.queryQipuId = queryQipuId;
                queryObject.minTime = parent.find("input[name=minTime]").val();
                queryObject.maxTime = parent.find("input[name=maxTime]").val();
                queryObject.isLive = isLiveType;
                queryObject.startDate = parent.find("input[name=minDateTime]").val();
                queryObject.endDate = parent.find("input[name=maxDateTime]").val();
                queryObject.minVideoOrder = parent.find("input[name=minVideoOrder]").val();
                queryObject.maxVideoOrder = parent.find("input[name=maxVideoOrder]").val();
                queryObject.albumName = $.trim(parent.find("input[name=albumName]").val());
                var channelObj = $($("select[name=channel]").children()[$("select[name=channel]")[0].selectedIndex]);
                var contentTypeObj = $($("select[name=contentType]").children()[$("select[name=contentType]")[0].selectedIndex]);
                queryObject.kvPair = [];
                queryObject.kvPair.push({value: channelObj.val(), name: "filter_EQL_channel"});
                queryObject.kvPair.push({value: contentTypeObj.val(), name: contentTypeObj.attr("name") });
                queryObject.customTags = parent.find("input[name=customTags]").val();
                self.queryInsert(queryObject)
            },

            queryInsert: function (sendObject) {
                var self = this;
                var checkArr = [];
                checkArr.push({value: sendObject.minTime, error: "最小时长需要数字格式", type: "positive"});
                checkArr.push({value: sendObject.minTime, error: "最小时长不能小于60秒", type: "ge", other: 60});
                if (sendObject.maxTime.length > 0) {
                    checkArr.push({value: sendObject.maxTime, error: "最大时长需要数字格式", type: "positive"});
                    checkArr.push({value: parseInt(sendObject.maxTime), error: "最小时长不能大于最大时长", type: "ge", other: parseInt(sendObject.minTime) });
                }
                if (sendObject.queryQipuId.length > 0) {
                    checkArr.push({value: sendObject.queryQipuId, error: "qipuId需要数字格式", type: "positive"});
                }

                if (!sendObject.isLive) {
                    if (sendObject.minVideoOrder.length > 0) {
                        checkArr.push({value: sendObject.minVideoOrder, error: "最小集数需非负整数", type: "number"});
                    }
                    if (sendObject.maxVideoOrder.length > 0) {
                        checkArr.push({value: sendObject.maxVideoOrder, error: "最大集数需要非负整数", type: "number"});
                    }
                    if (sendObject.minVideoOrder.length > 0 && sendObject.maxVideoOrder.length > 0) {
                        checkArr.push({value: parseInt(sendObject.maxVideoOrder), error: "终止集数必须大于等于开始集数", type: "ge", other: parseInt(sendObject.minVideoOrder) });
                    }
                    if (sendObject.customTags.length > 0) {
                        sendObject.customTags = sendObject.customTags.replace(/，/g, ",");
                    }
                    if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                        console.log("interrupt queryInsert")
                        return false;
                    }
                }

                if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt queryInsert")
                    return false;
                }
                if (sendObject.isLive) {
                    self.fillGridType2(sendObject);
                } else {
                    var task = self.task.platSettingsTask(self.dao.cfgName.platSettings, {channelId: self.dao.channelId});
                    EpgWeb.ajaxQueue.removeTask(task.regName);
                    EpgWeb.ajaxQueue.push(task.regName, task.options);
                    EpgWeb.ajaxQueue.afterLoadComplete(function () {
                        self.fillGridType1(sendObject);
                    });
                    EpgWeb.ajaxQueue.startLoad();
                }
            },

            batchInsertLiveProgram: function (tableId) {

                var gridElement = $("#" + tableId);
                var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                var ids = [];
                $.each(selectedtrArr, function (i, element) {
                    ids.push(parseInt($(element).attr("id")));
                })
                if (ids.length == 0) {
                    return;
                }
                Carousel.Util.addDisAble();
                Carousel.Config.saveIds = ids;
                Carousel.Config.invalidArr = [];
                Carousel.Util.batchAdd();
                console.log("ids " + JSON.stringify(ids));
            },

            batchInsertCarouselLibrary: function (tableId) {
                var gridElement = $("#" + tableId);
                var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                var ids = [];
                var self = this;
                $.each(selectedtrArr, function (i, element) {
                    ids.push(parseInt($(element).attr("id")));
                })
                if (ids.length == 0) {
                    return;
                }
                Carousel.Util.addDisAble();
                Carousel.Config.saveIds = ids;
                Carousel.Config.invalidArr = [];
                self.checkLibraryMulti();
                console.log("ids " + JSON.stringify(ids));
            },

            fillGridType1: function (sendObj) {
                var self = this;
                self.$grid1.clearGridData();
                var paramsData = Carousel.Util.getSearchParamsBySettings();
                //append base
                paramsData["filter_GTL_qipuId"] = 0;
                paramsData["t"] = 0;
                //page params
                paramsData["page.pageNo"] = 1;
                paramsData["page.order"] = "desc";
                paramsData["page.orderBy"] = "createTime";
                paramsData["page.pageSize"] = 30;

                if (sendObj.queryName.length > 0) {
                    paramsData["filter_LIKES_displayName"] = sendObj.queryName
                }
                if (sendObj.queryQipuId.length > 0) {
                    paramsData["filter_EQL_qipuId"] = sendObj.queryQipuId;
                }
                if (sendObj.minTime.length > 0) {
                    paramsData["filter_GEL_duration"] = parseInt(sendObj.minTime) * 1000;
                }
                if (sendObj.maxTime.length > 0) {
                    paramsData["filter_LEL_duration"] = parseInt(sendObj.maxTime) * 1000;
                }

                if (sendObj.minVideoOrder.length > 0) {
                    paramsData["filter_GEL_videoOrder"] = parseInt(sendObj.minVideoOrder);
                }
                if (sendObj.maxVideoOrder.length > 0) {
                    paramsData["filter_LEL_videoOrder"] = parseInt(sendObj.maxVideoOrder);
                }
                if (sendObj.albumName.length > 0) {
                    paramsData["filter_LIKES_albumDisplayName"] = sendObj.albumName;
                }
                if (sendObj.customTags.length > 0) {
                    paramsData["filter_INS_customTags"] = sendObj.customTags;
                }
                $.each(sendObj.kvPair, function (i, element) {
                    if (element.value.length > 0) {
                        paramsData[element.name] = element.value;
                    }
                })

                var requestData = {url: EpgWeb.Constant.thirdUrl_apis_search_area_url, type: "get", params: paramsData, needCookie: true};
                var parentView = $("#addProgramView");
                parentView.find("button[name=queryProgram]").attr("disable", "disabled");

                self.$grid1.setGridParam({page: 1, url: EpgWeb.urlConfig.redirect, loadtext: '加载中...', pageSize: 50,
                    datatype: "json",
                    loadui: "block", postData: {"request": JSON.stringify(requestData), timeSign: Date.now()}}).trigger("reloadGrid");

            },

            fillGridType2: function (sendObj) {
                var self = this;
                self.$grid2.clearGridData();
                var sendData = {startDate: "", endDate: ""};
                if (sendObj.endDate.length > 0) {
                    if (!EpgWeb.Plugin.Validate.checkDateFormat(sendObj.endDate)) {
                        EpgWeb.Plugin.showTips({content: "最大开始时间格式错误"})
                        return;
                    }
                    sendData.endDate = sendObj.endDate;
                }

                if (sendObj.startDate.length > 0) {
                    if (!EpgWeb.Plugin.Validate.checkDateFormat(sendObj.startDate)) {
                        EpgWeb.Plugin.showTips({content: "最小开始时间格式错误"})
                        return;
                    }
                    sendData.startDate = sendObj.startDate;
                } else {
                    var defaultDate = new Date();
                    sendData.startDate = Carousel.Util.quickDateFormat(defaultDate);
                    if (sendData.endDate.length > 0) {
                        if (sendData.startDate > sendData.endDate) {
                            sendData.startDate = "";
                        }
                    } else {
                        if (sendData.startDate < Carousel.Config.dateTime) {
                            sendData.startDate = Carousel.Config.dateTime;
                        }
                    }
                }
                sendData.pageSize = 50;
                sendData.qipuId = '';
                sendData.pname = '';
                sendData.maxTime = '';
                if (sendObj.queryQipuId.length > 0) {
                    sendData.qipuId = sendObj.queryQipuId;
                }
                if (sendObj.queryName.length > 0) {
                    sendData.pname = $.trim(sendObj.queryName);
                }
                sendData.minTime = sendObj.minTime;
                if (sendObj.maxTime.length > 0) {
                    sendData.maxTime = sendObj.maxTime;
                }

                $(".norecords").hide()
                self.$grid2.setGridParam({url: EpgWeb.urlConfig.programLiveQueryUrl, loadtext: '加载中...', page: 1,
                    datatype: "json",
                    loadui: "block", postData: sendData}).trigger("reloadGrid");
            },

            //--------CarouselInsert  end==========/


            //--------carousel automation library  start==========/
            runLibrary: function () {
                var self = this;
                self.libraryUseDlg();
                $("button[name=btn_automation_rule]").hide();
                $("button[name=btn_auto_rule]").hide();
                $("button[name=btn_automation_library]").hide();

                self.$grid = self.options.$grid
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramTypeTask(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getContentTypeTask(self.dao.cfgName.ContentType));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: self.dao.channelId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    Carousel.Config.IS_RULE_RUNNING = true;
                    Carousel.Util.queryVirtualRule({channelId:self.dao.channelId},function(flag){
                        if(flag){
                            self.startLibrary();
                        }
                    } );
                });
                EpgWeb.ajaxQueue.startLoad();
            },

            startLibrary: function () {
                var self = this;
                var channelData = self.dao.getChannel();
                if (!Carousel.Util.isCarouselCheck(channelData)) {
                    return;
                }
                self.initLibrary();
                self.bindLibraryBasicEvent();
            },
            initLibrary: function (options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIBRARY);
                self.$grid.jqGrid(gridConfig);
                self.$grid.setGridParam({page: 1, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: self.getLibraryParam()}).trigger("reloadGrid");

            },
            getLibraryParam: function () {
                var self = this;
                return  {channelId: self.dao.channelId};
            },
            bindLibraryBasicEvent: function () {
                var self = this;
                $("button[name=btn_insert]").bind("click", function (event) {
                    var toHref = "/epg/carousel_insert.html?fatherId=" + self.dao.channelId;
                    var currentDay = EpgWeb.Util.formatDateTimeFormat(new Date())
                    toHref += "&startTime=" + currentDay.substr(0, 10) + " 00:00:00";
                    Carousel.Util.openNewHtml(toHref);
                });

                $("button[name=btn_rule_start]").bind("click", function (event) {
                    Carousel.Util. queryVirtualRule( {channelId: self.dao.channelId} ,function(flag){
                        if(flag ){
                            if(!Carousel.Util.IS_RULE_RUNNING){
                                Carousel.Util.notifyRuleChangeStatus(Carousel.Config.ChangeStatus.STATUS_PROGRAM_RUN);
                            }
                        }
                    } );
                })
                $("button[name=btn_rule_stop]").bind("click", function (event) {

                    Carousel.Util.queryVirtualRule( {channelId: self.dao.channelId} ,function(flag){
                        if(flag ){
                            if(Carousel.Config.IS_RULE_RUNNING){
                                var msg = Carousel.Config.Hint.STOP_RULE_HINT;
                                SystemDialog.queryConfirm(msg, function (flag) {
                                    if (flag === true) {
                                        Carousel.Util.notifyRuleChangeStatus(Carousel.Config.ChangeStatus.STATUS_PROGRAM_IDLE)
                                    }
                                })
                            }
                        }
                    } );
                })

                self.$grid.jqGrid('navGrid', "#pager", {
                    edit: false,
                    add: false,
                    del: false,
                    search: false,
                    refresh: false
                });
                self.$grid.jqGrid('navButtonAdd', "#pager", {
                    caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                    onClickButton: function () {
                        if (Carousel.Config.IS_RULE_RUNNING) {
                            SystemDialog.queryAlert("规则执行中不能删除");
                            return;
                        }
                        var gridElement = $("#list");
                        var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                        var ids = [];
                        $.each(selectedtrArr, function (i, element) {
                            ids.push(parseInt($(element).attr("id")));
                        });

                        if (ids.length == 0) {
                            return;
                        }

                        Carousel.Util.episodeBatchDel(ids.join(","), self.dao.channelId);
                    }, position: "last", title: "批量删除", cursor: "pointer"
                });
            },
            //--------carousel automation library  end==========/


            //====================carouselRule start========================================/
            runRule: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.model = self.options.model;
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramType(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getLiveChannelType(self.dao.cfgName.liveChannelType));
                taskArr.push(self.task.getLiveType(self.dao.cfgName.LiveType));
                taskArr.push(self.task.getGradeType(self.dao.cfgName.episodeGradeType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startRule();
                })
                EpgWeb.ajaxQueue.startLoad();
            },

            startRule: function () {
                var self = this;
                var channelData = self.dao.getChannel();
                if (!Carousel.Util.isCarouselCheck(channelData)) {
                    return;
                }
                self.initRuleGrid();
                self.bindBasicRuleEvent();
            },
            initRuleGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_RUN);
                self.$grid.jqGrid(gridConfig);
                self.$grid.setGridParam({page: 1, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: {fatherId: self.dao.channelId}}).trigger("reloadGrid");
            },

            bindBasicRuleEvent: function () {
                var self = this;
                self.$grid.jqGrid('navGrid', "#pager", {
                    edit: false,
                    add: false,
                    del: false,
                    search: false,
                    refresh: false
                });
                self.$grid.jqGrid('navButtonAdd', "#pager", {
                    caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                    onClickButton: function () {
                        var gridElement = $("#list");
                        var dataOriginl = gridElement.jqGrid("getRowData");
                        var hiddenData = JSON.parse(dataOriginl[0].hiddenData);
                        var fatherId = hiddenData.fatherId;
                        var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                        var ids = [];
                        $.each(selectedtrArr, function (i, element) {
                            ids.push(parseInt($(element).attr("id")));
                        });
                        if (ids.length == 0) {
                            return;
                        }
                        // Carousel.Util.ruleDel()
                        //Carousel.Operation.programBatchDel(ids);
                        //   Carousel.Operation.ruleDel(ids.join(','), fatherId, "是否确认删除本页内所有已选择的过期规则？删除后不可恢复");
                    }, position: "last", title: "批量删除", cursor: "pointer"
                });
            },

            //====================carouselRule end========================================/

            //====================carouselAutomationRule start========================================/

            runAutomationRule: function () {

            },
            //====================carouselAutomationRule end========================================/


            //====================initSuggest start========================================/

            initSuggest: function () {
                var gridSelf = this;
                var albumSuggest = {
                    options: {
                        _beforeSuggest: function (callback) {
                            var task = gridSelf.task.platSettingsTask(gridSelf.dao.cfgName.platSettings, {channelId: gridSelf.dao.channelId});
                            EpgWeb.ajaxQueue.removeTask(task.regName);
                            var ajaxData = task.options;
                            self.dao.sendAjax(ajaxData.url, ajaxData.type, ajaxData.data, function (data) {
                                if (data != null && data.code == "A00000") {
                                    Carousel.ajaxManager.push(task.regName, task.options, data, false);
                                    callback.call();
                                } else {
                                    EpgWeb.Plugin.showTips({content: "发生异常", type: "error"});
                                }
                            })
                        },
                        _doSuggest: function (request, response, param) {
                            var self = this,
                                options = self.options,
                                url = options.url,
                                getParam = null,
                                term = $.trim(request.term),
                                getParam = options.getParam;
                            if (getParam) {
                                if ($.isFunction(options.getParam)) {
                                    param = $.extend(true, param, getParam.call(self, term));
                                } else if ($.isPlainObject(getParam)) {
                                    param = $.extend(true, param, getParam);
                                }
                            }
                            self._getSuggestData(url, options.method, param, $.proxy(self.options._handleResponse, self, request, response));
                        },
                        _handleResponse: function (request, response, data) {
                            var self = this,
                                options = self.options,
                                term = $.trim(request.term),
                                dataProcess = options.process,
                                ret = dataProcess.call(self, data, term);

                            ret = $.ui.autocomplete.filter(ret, term);

                            if (options.highlight) {
                                options.highlight.call(self, ret, self._displayKey, term);
                            }

                            self.result = ret;
                            if (ret.length > 0) {
                                Carousel.Util.checkQipuPlatformControl(response, ret);
                            }
                            //response
                        },
                        url: EpgWeb.urlConfig.redirect,
                        source: function (request, response) {
                            var self = this,
                                options = self.options,
                                term = $.trim(request.term),
                                url = null,
                                getParam = null,
                                param = {};
                            if (!term) {
                                return null;
                            }

                            if (!options.ignoreWord) {
                                //传递 word  term
                                param = {
                                    word: term
                                };
                            }

                            param = $.extend(true, options.otherParam, param);

                            if ($.isFunction(self.options._beforeSuggest)) {
                                self.options._beforeSuggest.call(self, function () {
                                    self.options._doSuggest.call(self, request, response, param)
                                })
                            } else {
                                self.options._doSuggest.call(self, request, response, param)
                            }
                        },
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        select: function (event, object) {
                            var msg = [];
                            var self = this;
                            if (object.item.hintMsgObj.missPPSClient) {
                                msg.push(Carousel.ErrorMsg.PPS_CLIENT_MSG);
                            }
                            if (object.item.hintMsgObj.missQIYIClient) {
                                msg.push(Carousel.ErrorMsg.QIYI_CLIENT_MSG);
                            }
                            if (object.item.hintMsgObj.missPPSRegion) {
                                msg.push(Carousel.ErrorMsg.PPS_REGION_MSG);
                            }
                            if (object.item.hintMsgObj.missQIYIRegion) {
                                msg.push(Carousel.ErrorMsg.QIYI_REGION_MSG);
                            }

                            self.value = "";
                            if (msg.length > 0) {
                                SystemDialog.queryConfirm(msg.join("<br>"), function (flag) {
                                    if (flag === true) {
                                        self.value = object.item.id + "";
                                        gridSelf.fillRuleView(object.item)
                                    }
                                });
                            } else {
                                self.value = object.item.id + "";
                                gridSelf.fillRuleView(object.item)
                            }
                            return false;
                        },
                        getParam: function (term) {
                            var currentTime = new Date().getTime();
                            var params = Carousel.Util.getSearchParamsBySettings();
                            params["word"] = term;
                            params["size"] = 20;
                            params["type"] = "displayName";
                            var requestData = {url: Carousel.Constant.thirdUrl_album_area_url, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: currentTime}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                EpgWeb.Plugin.showTips({content: "获取接口数据失败", type: "error"});
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            var currentTime = new Date().getTime();
                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["displayName"];
                                itemData["channelName"] = item["channelName"];
                                itemData["copyrightBeginTime"] = item["copyright"] ? item["copyright"][0].copyrightBeginTime : null;
                                itemData["copyrightEndTime"] = item["copyright"] ? item["copyright"][0].copyrightEndTime : null;
                                itemData["isPurchase"] = item["isPurchase"];
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                itemData["entityId"] = item["entityId"];
                                itemData["totalNum"] = item["totalNumberOfEpisodes"]
                                itemData.hintMsgObj = item.hintMsgObj;
                                itemData["pageUrl"] = item["pageUrl"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return "";
                           // return Carousel.Formatter.getTemplate(item)
                        },
                        header: Carousel.Util.template.albumSuggest(Carousel.Config.Header.albumSuggest)
                    }
                }
            },

            fillRuleView: function (element) {
                var self = this;
                Carousel.Config.ruleSelectElement = element;
                if (element.totalNum > 0) {
                    $("input[name=totalNum]").val(element.totalNum);
                }

                $("#loadLegoMessage").dialog("open");
                Carousel.Util.queryTotalNum(element.entityId, function () {
                    $("#loadLegoMessage").dialog("close");
                    if (element.totalNum == 0) {
                        element.totalNum = parseInt($("input[name=actualNum]").val(), 10);
                        $("input[name=totalNum]").val($("input[name=actualNum]").val());
                    }
                    self.checkTotalAndActual();
                    console.log("填充数据完成");
                });
            },

            checkTotalAndActual: function () {
                var actualNum = $("input[name=actualNum]").val();
                var totalNum = $("input[name=totalNum]").val();
                $("input[name=check_follow]").removeAttr("checked");
                $("input[name=check_repeat]").removeAttr("checked");
                $("input[name=check_follow]").attr("disabled", "disabled");
                $("input[name=check_repeat]").attr("disabled", "disabled");
                if (actualNum === "") {
                    EpgWeb.Plugin.showTips({content: "奇谱没有相应数据", type: "error"});
                    return;
                }
                if (actualNum == totalNum) {
                    $("input[name=check_repeat]").removeAttr("disabled");
                } else {
                    $("input[name=check_follow]").removeAttr("disabled");
                }
            },

            //====================initSuggest end========================================/

            //====================initDialog start========================================/
            dayListUseDlg: function () {
                var self = this;
                self.initLoadLegoDlg();
                self.initDelMessageDlg();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');

            },
            insertUseDlg: function () {
                var self = this;
                self.initLoadLegoDlg();
                self.initBatchResponseDiv();
                self.initQueryMessageDlg();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            libraryUseDlg: function () {
                var self = this;
                self.initLoadLegoDlg();
                self.initBatchResponseDiv();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },

            initLoadLegoDlg: function () {
                $("#loadLegoMessage").dialog({
                    title: "数据加载",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                });
            },
            initDelMessageDlg: function () {
                $("#delMessage").dialog({
                    title: "数据删除",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: {
                        "ok": function () {
                            $(this).dialog("close");
                        },
                        "cancel": function () {
                            $(this).dialog("close");
                        }
                    }
                })
            },
            initQueryMessageDlg: function () {
                var self = this;
                $("#queryMessage").dialog({
                    title: "是否继续操作",
                    autoOpen: false,
                    width: 255,
                    minHeight: 150,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                })
                $("input[name=btn_nil]").bind("click", function (evt) {
                    $("#queryMessage").dialog("close");
                })
                $("input[name=btn_jump_library]").bind("click", function (evt) {
                    var toUrl = "/epg/carousel_automation_library.html?fatherId=" + self.dao.channelId
                    window.location.href = toUrl;
                })
            },

            initCopyRightDlg: function () {
                $("#notifyCopyRightDlg").dialog({
                    title: "版权到期提醒",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "继续",
                            click: function () {
                                $(this).dialog("close");
                              //  doHandler(true);
                            }
                        },
                        {
                            text: "中断",
                            click: function () {
                                $(this).dialog("close");
                             //   doHandler(false);
                            }
                        }
                    ]
                });
            },

            initBatchResponseDiv: function () {
                $("#batchResponseDiv").dialog({
                    title: "数据核查汇总",
                    autoOpen: false,
                    width: 440,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function (event) {
                        Carousel.Util.removeDisAble();
                    },
                    buttons: [
                        {
                            text: "继续",
                            click: function () {

                                Carousel.Util.addDisAble();
                                if (Carousel.Config.saveIds == null) {
                                    Carousel.Util.removeDisAble();
                                } else {
                                    Carousel.Util.batchAddByBindModel();
                                }
                                $(this).dialog("close");
                            }
                        },
                        {
                            text: "中断",
                            click: function () {
                                $(this).dialog("close");
                            }
                        }
                    ]
                })
            },

            initAdvertDialog:function(){
                $("#advert_dlg").dialog({
                    title: "编辑广告点",
                    autoOpen: false,
                    width: 440,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if(Carousel.Dao.cfgName.ad_selected > 0){
                                    Carousel.Dao.postModifyAdvert({id:Carousel.Dao.cfgName.ad_selected,  enable:   parseInt( $("input[name=advertEnable]:checked").val()) }, function (data) {
                                        Carousel.Util.reloadHandler(data);
                                    })
                                }
                                $(this).dialog("close");
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                Carousel.Dao.cfgName.ad_selected = 0;
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
            },

            //====================================================//
            initWeekToolBar: function () {
                var self = this;
                Carousel.Util.WeekManager = EpgWeb.Util.createWeekManager($("#dayRange div label"));
                var weekRangeLabel = $("#weekRange label");
                $(weekRangeLabel[0]).bind("click", function () {
                    Carousel.Util.WeekManager.preWeek();
                });
                $(weekRangeLabel[1]).bind("click", function () {
                    self.updateTableByDate(Carousel.Util.WeekManager.quickToCurrentWeek());
                })
                $(weekRangeLabel[2]).bind("click", function () {
                    Carousel.Util.WeekManager.nextWeek()
                })
                $("button.left").bind("click", function () {
                    Carousel.Util.WeekManager.preWeek()
                })

                $("button.right").bind("click", function () {
                    Carousel.Util.WeekManager.nextWeek()
                })

                $("#dayRange div label").bind("click", function (event) {
                    var aChild = event.currentTarget;
                    $(aChild).parent().find("label").removeClass("selected");
                    $(aChild).addClass("selected");
                    self.updateTableByDate(aChild.getAttribute("query-date"))
                })
                self.updateTableByDate(Carousel.Util.WeekManager.quickToCurrentWeek());
            },
            updateTableByDate: function (lDateFormat) {
                var self = this;
                self.config.dateTime = lDateFormat;
                self.$grid.setGridParam({page: 1, url: EpgWeb.urlConfig.programList, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: self.getListParam()}).trigger("reloadGrid");
            }
            //====================================================//
        })
    }
);
/**
 * Copyright 2015 Qiyi.com All rights reserved.
 *
 * file: epg.js
 * path: js-src/
 * description: epg业务合并文件，通过该文件引入业务功能模块的js文件
 *              配置文件将用来生成合并文件
 * author: jiegang@qiyi.com
 * date: 2015-1-6
 */
define(
    'epg2', [
        "../ancestor/Ancestor",
        "../ancestor/Ancestor.Crop",
        "../ancestor/Ancestor.Config",
        "../ancestor/Ancestor.Util",
        "../ancestor/Ancestor.Grid",
        "../ancestor/Ancestor.Dao",
        "../ancestor/Ancestor.Upload",
        "../epg2/EpgWeb",
        "../epg2/EpgWeb.Util",
        "../epg2/EpgWeb.Plugin",
        "../epg2/EpgWeb.Dao",
        "../epg2/EpgWeb.Task",
        "../epg2/EpgWeb.PingBack",
        "../epg2/EpgWeb.PingBackCost",
        "../program/Program",
        "../program/Program.Action",
        "../program/Program.Config",
        "../program/Program.Dao",
        "../program/Program.Util",
        "../program/Program.Task",
        "../program/Program.Grid",
        "../zhibo/Zhibo",
        "../zhibo/Zhibo.Action",
        "../zhibo/Zhibo.Config",
        "../zhibo/Zhibo.Dao",
        "../zhibo/Zhibo.Util",
        "../zhibo/Zhibo.Task",
        "../zhibo/Zhibo.Grid",
        "../live2VOD/live2VOD",
        "../live2VOD/live2VOD.Action",
        "../live2VOD/live2VOD.Config",
        "../live2VOD/live2VOD.Dao",
        "../live2VOD/live2VOD.Util",
        "../live2VOD/live2VOD.Edit",
        "../live2VOD/live2VOD.Grid",
        "../broadcast/Broadcast",
        "../broadcast/Broadcast.Action",
        "../broadcast/Broadcast.Config",
        "../broadcast/Broadcast.Dao",
        "../broadcast/Broadcast.Util",
        "../broadcast/Broadcast.Task",
        "../broadcast/Broadcast.Edit",
        "../broadcast/Broadcast.Grid",
        "../statistic/Statistic",
        "../statistic/Statistic.Action",
        "../statistic/Statistic.Config",
        "../statistic/Statistic.Dao",
        "../statistic/Statistic.Util",
        "../statistic/Statistic.Grid",
        "../statistic/Statistic.Process",
        "../carousel/Carousel",
        "../carousel/Carousel.Action",
        "../carousel/Carousel.Config",
        "../carousel/Carousel.Dao",
        "../carousel/Carousel.Util",
        "../carousel/Carousel.Task",
        "../carousel/Carousel.AutomationRuleGrid",
        "../carousel/Carousel.Grid"
    ],

    function() {
        console.log('epg2 load done:', 'epg2');
        if (SystemDialog && SystemDialog.initSystemDialog) {
            SystemDialog.initSystemDialog();
        }
    }

);
